Jump to content

Module:String: Difference between revisions

1,301 bytes added ,  11 years ago
Continuing trials and tribulations of string trimming and Wikipedia template quirks
m>Dragons flight
(Update to allow for unnamed parameters. This is necessary because some string function need to preserve leading / trailing whitespace in order to work properly.)
m>Dragons flight
(Continuing trials and tribulations of string trimming and Wikipedia template quirks)
Line 17: Line 17:
function str.match( frame )
function str.match( frame )
     return mw.ustring.match( frame.args.s, frame.args.pattern, tonumber( frame.args.i ) )
     return mw.ustring.match( frame.args.s, frame.args.pattern, tonumber( frame.args.i ) )
end
--[====[
pos
This function returns a single character from the target string at position pos.
Usage:
{{#invoke:String|pos|target_string|index_value}}
OR
{{#invoke:String|pos|target=target_string|pos=index_value}}
Parameters
    target: The string to search
    pos: The index for the character to return
If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from the target string.  In some circumstances this is desirable, in
other cases one may want to preserve the whitespace.
The first character has an index value of 1.
If one requests a negative value, this function will select a character by counting backwards
from the end of the string.  In other words pos = -1 is the same as asking for the last character.
A requested value of zero, or a value greater than the length of the string returns an error.
]====]
function str.pos( frame )
    local new_args = str._getParameters( frame.args, {'target', 'pos'} );
    local target_str = new_args['target'] or '';
    local pos = tonumber( new_args['pos'] ) or 0;
    if pos == 0 or math.abs(pos) > mw.ustring.len( target_str ) then
        return '<strong class="error">String index out of range</strong>';
    end   
   
    return mw.ustring.sub( target_str, pos, pos );
end
end


Line 38: Line 75:
     local target_str = new_args['target'] or '';
     local target_str = new_args['target'] or '';


if target_str == '' then
    if target_str == '' then
         return 1;
         return 1;
     end     
     end     
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.