הבדלים בין גרסאות בדף "יחידה:String"

מתוך ויקיסוגיה
קפיצה לניווט קפיצה לחיפוש
תגית: שוחזרה
(ביטול גרסה 19057 של מוטל'ה (שיחה))
תגית: ביטול
 
שורה 1: שורה 1:
--[=[
--[[


This module is based on idea and original code of [[User:IKhitron]].
This module is intended to provide access to basic string functions.


the source of this module is in //he.wikipedia.org/wiki/Module:ParamValidator
Most of the functions provided here can be invoked with named parameters,
unnamed parameters, or a mixture.  If named parameters are used, Mediawiki will
automatically remove any leading or trailing whitespace from the parameter.
Depending on the intended use, it may be advantageous to either preserve or
remove such whitespace.


main purpose: use "templatedata" to verify the parameters passed to a template
Global options
    ignore_errors: If set to 'true' or 1, any error condition will result in
        an empty string being returned rather than an error message. 
       
    error_category: If an error occurs, specifies the name of a category to
        include with the error message.  The default category is 
        [Category:Errors reported by Module String].
       
    no_category: If set to 'true' or 1, no category will be added if an error
        is generated.
       
Unit tests for this module are available at Module:String/tests.
]]


Terminology: "numeric parameter" means order-based parameter. e.g. if the template is transcluded like so {{x  | k |  | a = m | b = }}
local str = {}
"a" and "b" are "named" parameters, and there are 2 "numeric", or order based parameters, 1 and 2.
we say that the value of a is "m", the value of 1 is "k", and "b" and 2 are "empty".


This module exports two functions: calculateViolations( frame, subpages ), and validateParams( frame ).
--[[
len


calculateViolations( frame, subpages ) finds templatedata, in template page or in one of its subpages in the list, if provided.
This function returns the length of the target string.
it returns a table with the violations. if there are none, the table is empty. otherwise it has the structure
{
violation1 = { param1 = value1, param2 = value2 },
violation2 = { ... },
...
}


violation1, violation2 etc. are one of the names of specific violations, as described below.
Usage:
param1, param2 etc. are either the names of parameter passed to the template, or defined in templatedata.
{{#invoke:String|len|target_string|}}
value1, value2 etc. are the values passed to the template, or an empty string if no such parameter was passed.
OR
{{#invoke:String|len|s=target_string}}


the different violations are as follow:
Parameters
* "no-templatedata": no valid tempaltedata was found in tempalte page, or documentation subpage
    s: The string whose length to report
* "undeclared": named parameters with non-empty value, does not exist in templatedata
* "empty-undeclared": named parameters with empty value, does not exist in templatedata
* "undeclared-numeric": numeric parameters with non-empty value, does not exist in templatedata
* "empty-undeclared-numeric": numeric parameters with empty value, does not exist in templatedata
* "deprecated":  parameters with non-empty value, marked as "deprecated" in tempaltedata
* "empty-deprecated":  parameters with empty value, marked as "deprecated" in tempaltedata
* "empty-required": missing or empty parameter marked as "required" in tempaltedata
* "incompatible": a non-empty parameter passed to the template, incompatible with the parameter type defined in templatedata
* "duplicate": a value is passed for the same parameter (or any of its aliases) more than once


If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from the target string. 
]]
function str.len( frame )
    local new_args = str._getParameters( frame.args, {'s'} );
    local s = new_args['s'] or '';
    return mw.ustring.len( s )
end
--[[
sub
This function returns a substring of the target string at specified indices.
Usage:
{{#invoke:String|sub|target_string|start_index|end_index}}
OR
{{#invoke:String|sub|s=target_string|i=start_index|j=end_index}}
Parameters
    s: The string to return a subset of
    i: The fist index of the substring to return, defaults to 1.
    j: The last index of the string to return, defaults to the last character.
   
The first character of the string is assigned an index of 1.  If either i or j
is a negative value, it is interpreted the same as selecting a character by
counting from the end of the string.  Hence, a value of -1 is the same as
selecting the last character of the string.


The second function, validateParams( frame ), can be called from the tempalte' using #invoke.
If the requested indices are out of range for the given string, an error is
it expects a parameter named "options", which contains the definition of the output. typically, it's used by placing something like so:
reported.
]]
function str.sub( frame )
    local new_args = str._getParameters( frame.args, { 's', 'i', 'j' } );
    local s = new_args['s'] or '';
    local i = tonumber( new_args['i'] ) or 1;
    local j = tonumber( new_args['j'] ) or -1;
   
    local len = mw.ustring.len( s );


<includeonly>{{#invoke:ParamValidator | validateParams | options = {{PV default options}} }}</includeonly>
    -- Convert negatives for range checking
    if i < 0 then
        i = len + i + 1;
    end
    if j < 0 then
        j = len + j + 1;
    end
   
    if i > len or j > len or i < 1 or j < 1 then
        return str._error( 'String subset index out of range' );
    end
    if j < i then
        return str._error( 'String subset indices out of order' );
    end
   
    return mw.ustring.sub( s, i, j )
end


at the top of the template (be mindful not to add extra spaces and newlines to the template).
--[[
to bypass some mediawiki limitation, it is also possible to pass the options as "module", like so (use one of the two, but not both):
This function implements that features of {{str sub old}} and is kept in order
<includeonly>{{#invoke:ParamValidator | validateParams | module_options = Module:PV default options}} }}</includeonly>
to maintain these older templates.
]]
function str.sublength( frame )
    local i = tonumber( frame.args.i ) or 0
    local len = tonumber( frame.args.len )
    return mw.ustring.sub( frame.args.s, i + 1, len and ( i + len ) )
end


the first form expects a template named "Template:PV default options" which contains the options, and the 2nd form expects a module,
--[[
suitable for mw.loadData(), which returns a map of namespace => options (i.e. { [0] = <options>, [2] => <options> } .... )
match


the options parameter should be a JSON-encoded string, defining the output, and some special behaviors.
This function returns a substring from the source string that matches a  
the example above assumes that a wiki page named [[Template:PV default options]] exists, and contains valid JSON string.
specified pattern.
for each of the violations defined above, "options" may define an output string, so basically, "options" looks like so:
{
violation1: outputstring1,
violation2: outputstring2,
.... ,
behavior1: some value,
....
}


not all violations have to be defined. a violation not defined in "options" will be ignored.
Usage:
{{#invoke:String|match|source_string|pattern_string|start_index|match_number|plain_flag|nomatch_output}}
OR
{{#invoke:String|pos|s=source_string|pattern=pattern_string|start=start_index
    |match=match_number|plain=plain_flag|nomatch=nomatch_output}}


when invoked, it extract "subpages" from the options parameter, and calls:
Parameters
  calculateViolations( frame, subpages )
    s: The string to search
if the returned table is empty, no violation were found, and an empty string is returned and nothing else happens.
    pattern: The pattern or string to find within the string
    start: The index within the source string to start the search.  The first
        character of the string has index 1.  Defaults to 1.
    match: In some cases it may be possible to make multiple matches on a single
        string. This specifies which match to return, where the first match is
        match= 1.  If a negative number is specified then a match is returned
        counting from the last match.  Hence match = -1 is the same as requesting
        the last match.  Defaults to 1.
    plain: A flag indicating that the pattern should be understood as plain
        text.  Defaults to false.
    nomatch: If no match is found, output the "nomatch" value rather than an error.


otherwise, for each of the violations, i.e., the keys of the returned table, when "options" contains this key,
If invoked using named parameters, Mediawiki will automatically remove any leading or
the corresonding value is appended to the output.
trailing whitespace from each string. In some circumstances this is desirable, in
other cases one may want to preserve the whitespace.


some further processing is done:
If the match_number or start_index are out of range for the string being queried, then
1) several tokens are replaced with calculated values. these are described below.
this function generates an error. An error is also generated if no match is found.
2) some "meta" violations are calculated: when any none-ignored violation occured,
If one adds the parameter ignore_errors=true, then the error will be suppressed and  
the "any" meta-violation is added to the output in the same way,  
an empty string will be returned on any failure.
i.e. the string keyed by "any" in the options is appended to output with appropriate substitutions.
similarly, "multiple" meta-violation is created when more than one type of non-ignored violations occured.
3) if the output is not empty, a prefix and suffix strings are prepended and appended to it.  


these are the tokens and the replacement.
For information on constructing Lua patterns, a form of [regular expression], see:
* "templatename": full template name, including namespace.
* "tname_naked": template name without namespace.
* "paramname":  comma-separated list of parameters
* "paramandvalue": is replaced by comma-separated list of "name: value" pairs of parameters and values
the first two are applied to the whole output, including the suffux and prefix,
and the rest are applied to the individual violations, each with its own list of offending parameters and values.


* http://www.lua.org/manual/5.1/manual.html#5.4.1
* http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Patterns
* http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Ustring_patterns


the rest of the if the value of some keys is null, this error condition will be ignored, and not counted when calculating "any" and "multiple" conditions.
]]
function str.match( frame )
    local new_args = str._getParameters( frame.args, {'s', 'pattern', 'start', 'match', 'plain', 'nomatch'} );
    local s = new_args['s'] or '';
    local start = tonumber( new_args['start'] ) or 1;
    local plain_flag = str._getBoolean( new_args['plain'] or false );
    local pattern = new_args['pattern'] or '';
    local match_index = math.floor( tonumber(new_args['match']) or 1 );
    local nomatch = new_args['nomatch'];
   
    if s == '' then
        return str._error( 'Target string is empty' );
    end
    if pattern == '' then
        return str._error( 'Pattern string is empty' );
    end
    if math.abs(start) < 1 or math.abs(start) > mw.ustring.len( s ) then
        return str._error( 'Requested start is out of range' );
    end
    if match_index == 0 then
        return str._error( 'Match index is out of range' );
    end
    if plain_flag then
        pattern = str._escapePattern( pattern );
    end
   
    local result
    if match_index == 1 then
        -- Find first match is simple case
        result = mw.ustring.match( s, pattern, start )
    else
        if start > 1 then
            s = mw.ustring.sub( s, start );
        end
       
        local iterator = mw.ustring.gmatch(s, pattern);
        if match_index > 0 then
            -- Forward search
            for w in iterator do
                match_index = match_index - 1;
                if match_index == 0 then
                    result = w;
                    break;
                end
            end   
        else
            -- Reverse search
            local result_table = {};
            local count = 1;
            for w in iterator do
                result_table[count] = w;
                count = count + 1;
            end
           
            result = result_table[ count + match_index ];           
        end
    end       
   
    if result == nil then
        if nomatch == nil then
            return str._error( 'Match not found' );
        else
            return nomatch;
        end
    else
        return result;
    end
end


some other optional fields can be passed via options:
--[[
* "doc-subpage": can be either a string, or a list (in square bracktes) of strings, indicating subpages of the template
pos
that may contain templatedata.
* "ignore": list of patterns. any parameter whose name matches any pattern, will not considered in violation of any of the rules.
* "skip-empty-numeric": if a quoted number, the module will ignore non-declared empty numeric parameters up to this number
* "wrapper-prefix": openning wrapper element of outpot (defaults to "<div class = 'paramvalidator-wrapper'>")
* "wrapper-suffix": closing wrapper element of output (defaults to "</div>")


additional option parameters, named options1, options2, etc. can be passed. any entry defined in these options will
This function returns a single character from the target string at position pos.
override the previous value. a typical use may be like so:


Usage:
typically, this JSON structure will be placed in a separate template, and retrieved for the module-use as shown above.
{{#invoke:String|pos|target_string|index_value}}
<includeonly>{{#invoke:ParamValidator | validateParams | options = {{PV default options}} | options1 = {"key":"value"} }}</includeonly>
OR
"key" can override any of the options fields described above.
{{#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.


local util = {
The first character has an index value of 1.
empty = function( s )  
 
return s == nil  or type( s ) == 'string' and mw.text.trim( s ) == ''  
If one requests a negative value, this function will select a character by counting backwards
end
from the end of the string.  In other words pos = -1 is the same as asking for the last character.
,  
 
extract_options = function( frame, optionsPrefix )
A requested value of zero, or a value greater than the length of the string returns an error.
optionsPrefix = optionsPrefix or 'options'
]]
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 str._error( 'String index out of range' );
    end  
   
    return mw.ustring.sub( target_str, pos, pos );
end
 
--[[
str_find
 
This function duplicates the behavior of {{str_find}}, including all of its quirks.
This is provided in order to support existing templates, but is NOT RECOMMENDED for
new code and templates.  New code is recommended to use the "find" function instead.


local options, n, more = {}
Returns the first index in "source" that is a match to "target". Indexing is 1-based,
if frame.args['module_options'] then
and the function returns -1 if the "target" string is not present in "source".
local module_options = mw.loadData( frame.args['module_options'] )
if type( module_options ) ~= 'table' then return {} end
local title = mw.title.getCurrentTitle()
local local_ptions = module_options[ title.namespace ] or module_options[ title.nsText ] or {}
for k, v in pairs( local_ptions ) do options[k] = v end
end
repeat
ok, more = pcall( mw.text.jsonDecode, frame.args[optionsPrefix .. ( n or '' )] )
if ok and type( more ) == 'table' then
for k, v in pairs( more ) do options[k] = v end
end
n = ( n or 0 ) + 1
until not ok


return options
Important Note: If the "target" string is empty / missing, this function returns a
end
value of "1", which is generally unexpected behavior, and must be accounted for
,
separatetly.
build_namelist = function ( template_name, sp )
]]
local res = { template_name }
function str.str_find( frame )
if sp then
    local new_args = str._getParameters( frame.args, {'source', 'target'} );
if type( sp ) == 'string' then sp = { sp } end
    local source_str = new_args['source'] or '';
for _, p in ipairs( sp ) do table.insert( res, template_name .. '/' .. p ) end
    local target_str = new_args['target'] or '';
end
return res
end
,
table_empty = function( t ) -- normally, test if next(t) is nil, but for some perverse reason, non-empty tables returned by loadData return nil...
if type( t ) ~= 'table' then return true end
for a, b in pairs( t ) do return false end
return true
end
,
}


local function _readTemplateData( templateName )
    if target_str == '' then
local title = mw.title.makeTitle( 0, templateName ) 
        return 1;
local templateContent = title and title.exists and title:getContent() -- template's raw content
    end   
local capture = templateContent and mw.ustring.match( templateContent, '<templatedata%s*>(.*)</templatedata%s*>' ) -- templatedata as text
   
-- capture = capture and mw.ustring.gsub( capture, '"(%d+)"', tonumber ) -- convert "1": {} to 1: {}. frame.args uses numerical indexes for order-based params.
    local start = mw.ustring.find( source_str, target_str, 1, true )
local trailingComma = capture and mw.ustring.find( capture, ',%s*[%]%}]' ) -- look for ,] or ,} : jsonDecode allows it, but it's verbotten in json
    if start == nil then
if capture and not trailingComma then return pcall( mw.text.jsonDecode, capture ) end
        start = -1
return false
    end
   
    return start
end
end


local function readTemplateData( templateName )
--[[
if type( templateName ) == 'string' then
find
templateName = { templateName, templateName .. '/' .. docSubPage }
 
end
This function allows one to search for a target string or pattern within another
if type( templateName ) == "table" then
string.
for _, name in ipairs( templateName ) do
 
local td, result = _readTemplateData( name )  
Usage:
if td then return result end
{{#invoke:String|find|source_str|target_string|start_index|plain_flag}}
end
OR
end
{{#invoke:String|find|source=source_str|target=target_str|start=start_index|plain=plain_flag}}
return nil
 
Parameters
    source: The string to search
    target: The string or pattern to find within source
    start: The index within the source string to start the search, defaults to 1
    plain: Boolean flag indicating that target should be understood as plain
        text and not as a Lua style regular expression, defaults to true
 
If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from the parameter.  In some circumstances this is desirable, in
other cases one may want to preserve the whitespace.
 
This function returns the first index >= "start" where "target" can be found
within "source".  Indices are 1-based.  If "target" is not found, then this
function returns 0.  If either "source" or "target" are missing / empty, this
function also returns 0.
 
This function should be safe for UTF-8 strings.
]]
function str.find( frame )
    local new_args = str._getParameters( frame.args, {'source', 'target', 'start', 'plain' } );
    local source_str = new_args['source'] or '';
    local pattern = new_args['target'] or '';
    local start_pos = tonumber(new_args['start']) or 1;
    local plain = new_args['plain'] or true;
       
    if source_str == '' or pattern == '' then
        return 0;
    end   
   
    plain = str._getBoolean( plain );
 
    local start = mw.ustring.find( source_str, pattern, start_pos, plain )
    if start == nil then
        start = 0
    end
   
    return start
end
end


--[[
replace
This function allows one to replace a target string or pattern within another
string.


-- this is the function to be called by other modules. it expects the frame, and then an optional list of subpages, e.g. { "Documentation" }.
Usage:
-- if second parameter is nil, only tempalte page will be searched for templatedata.
{{#invoke:String|replace|source_str|pattern_string|replace_string|replacement_count|plain_flag}}
local function calculateViolations( frame, subpages )
OR
-- used for parameter type validy test. keyed by TD 'type' string. values are function(val) returning bool.
{{#invoke:String|replace|source=source_string|pattern=pattern_string|replace=replace_string|
local type_validators = {  
  count=replacement_count|plain=plain_flag}}
['number'] = function( s ) return mw.language.getContentLanguage():parseFormattedNumber( s ) end
}
local function compatible( typ, val )
local func = type_validators[typ]
return type( func ) ~= 'function' or util.empty( val ) or func( val )
end
local function list_empty_or_contains(ar, searched)
if not ar or #ar == 0 then return true end
for _, val in ipairs(ar) do if val == searched then return true end end
return false
end
local t_frame = frame:getParent()
local t_args, template_name = t_frame.args, t_frame:getTitle()
local td_source = util.build_namelist( template_name, subpages )
local templatedata = readTemplateData( td_source )
local td_params = templatedata and templatedata.params
local all_aliases, all_series = {}, {}
if not td_params then return { ['no-templatedata'] = { [''] = '' } } end
-- from this point on, we know templatedata is valid.


local res = {} -- before returning to caller, we'll prune empty tables
Parameters
    source: The string to search
    pattern: The string or pattern to find within source
    replace: The replacement text
    count: The number of occurences to replace, defaults to all.
    plain: Boolean flag indicating that pattern should be understood as plain
        text and not as a Lua style regular expression, defaults to true
]]
function str.replace( frame )
    local new_args = str._getParameters( frame.args, {'source', 'pattern', 'replace', 'count', 'plain' } );
    local source_str = new_args['source'] or '';
    local pattern = new_args['pattern'] or '';
    local replace = new_args['replace'] or '';
    local count = tonumber( new_args['count'] );
    local plain = new_args['plain'] or true;
       
    if source_str == '' or pattern == '' then
        return source_str;
    end   
    plain = str._getBoolean( plain );


-- allow for aliases
    if plain then
for _, p in pairs( td_params ) do for _, alias in ipairs( p.aliases or {} ) do
        pattern = str._escapePattern( pattern );
all_aliases[alias] = p
        replace = mw.ustring.gsub( replace, "%%", "%%%%" ); --Only need to escape replacement sequences.
if tonumber(alias) then all_aliases[tonumber(alias)] = p end
    end
end end
   
    local result;


-- handle undeclared and deprecated
    if count ~= nil then
local already_seen = {}
        result = mw.ustring.gsub( source_str, pattern, replace, count );
local series = frame.args['series']
    else
for p_name, value in pairs( t_args ) do
        result = mw.ustring.gsub( source_str, pattern, replace );
local tp_param, noval, numeric, table_name = td_params[p_name] or all_aliases[p_name], util.empty( value ), tonumber( p_name )
    end       
local hasval = not noval


if not tp_param and series then -- 2nd chance. check to see if series
    return result;
for s_name, p in pairs(td_params) do
end
if mw.ustring.match( p_name, '^' .. s_name .. '%d+' .. '$') then
-- mw.log('found p_name '.. p_name .. '  s_name:' .. s_name, ' p is:', p) debugging series support
tp_param = p
end -- don't bother breaking. td always correct.
end
end
if not tp_param then -- not in TD: this is called undeclared
-- calculate the relevant table for this undeclared parameter, based on parameter and value types
table_name =
noval and numeric and 'empty-undeclared-numeric' or
noval and not numeric and 'empty-undeclared' or
hasval and numeric and 'undeclared-numeric' or
'undeclared' -- tzvototi nishar.
else -- in td: test for deprecation and mistype. if deprecated, no further tests
table_name = tp_param.deprecated and hasval and 'deprecated'
or tp_param.deprecated and noval and 'empty-deprecated'
or not compatible( tp_param.type, value ) and 'incompatible'
or not series and already_seen[tp_param] and hasval and 'duplicate'
or hasval and not list_empty_or_contains(tp_param.suggestedvalues , value) and 'unsuggested-value'


--[[
already_seen[tp_param] = hasval
"Reverse" reverses a string, a'la string.reverse()
end
]]
-- report it.
str.reverse = function( frame )
if table_name then
    local tab = mw.text.split( frame.args[1] or '', '' )
res[table_name] = res[table_name] or {}
    local restab = {}
res[table_name][p_name] = value
    for i = #tab, 1, -1 do table.insert( restab, tab[i] ) end
end
    return table.concat( restab )
end
-- test for empty/missing paraeters declared "required"  
for p_name, param in pairs( td_params ) do
if param.required and util.empty( t_args[p_name] ) then
local is_alias
for _, alias in ipairs( param.aliases or {} ) do is_alias = is_alias or not util.empty( t_args[alias] ) end
if not is_alias then
res['empty-required'] = res['empty-required'] or {}  
res['empty-required'][p_name] = ''
end
end
end
return res
end
end


-- wraps report in hidden frame
str['היפוך'] = str.reverse
local function wrapReport(report, template_name, options)
 
if util.empty( report ) then return '' end
--[[
local naked = mw.title.new( template_name )['text']
Helper function that populates the argument list given that user may need to use a mix of
named and unnamed parameters.  This is relevant because named parameters are not
mw.log(report)
identical to unnamed parameters due to string trimming, and when dealing with strings
report = ( options['wrapper-prefix'] or "<div class = 'paramvalidator-wrapper'><span class='paramvalidator-error'>" )
we sometimes want to either preserve or remove that whitespace depending on the application.
.. report
]]
.. ( options['wrapper-suffix'] or "</span></div>" )
function str._getParameters( frame_args, arg_list )
    local new_args = {};
report = mw.ustring.gsub( report, 'tname_naked', naked )
    local index = 1;
report = mw.ustring.gsub( report, 'templatename', template_name )
    local value;
return report
   
    for i,arg in ipairs( arg_list ) do
        value = frame_args[arg]
        if value == nil then
            value = frame_args[index];
            index = index + 1;
        end
        new_args[arg] = value;
    end
   
    return new_args;
end       
 
--[[
Helper function to handle error messages.
]]
function str._error( error_str )
    local frame = mw.getCurrentFrame();
    local error_category = frame.args.error_category or 'שגיאות טיפול במחרוזת';
    local ignore_errors = frame.args.ignore_errors or false;
    local no_category = frame.args.no_category or false;
   
    if str._getBoolean(ignore_errors) then
        return '';
    end
   
    local error_str = '<strong class="error">String Module Error: ' .. error_str .. '</strong>';
    if error_category ~= '' and not str._getBoolean( no_category ) then
    if mw.title.getCurrentTitle().namespace ~= 10 then
        error_str = '[[Category:' .. error_category .. ']]' .. error_str;
        end
    end       
   
    return error_str;
end
end


-- this is the "user" version, called with {{#invoke:}} returns a string, as defined by the options parameter
--[[
local function validateParams( frame )
Helper Function to interpret boolean strings
]]
-- for purple pages:
function str._getBoolean( boolean_str )
if frame:getParent().args['skip parameters validation'] then return '[[ קטגוריה:דפים עם שגיאות פרמטריות שקיבלו חנינה]]' end
    local boolean_value;
local options, report, template_name = util.extract_options( frame ), '', frame:getParent():getTitle()
   
    if type( boolean_str ) == 'string' then
        boolean_str = boolean_str:lower();
        if boolean_str == 'false' or boolean_str == 'no' or boolean_str == '0'  
                or boolean_str == '' then
            boolean_value = false;
        else
            boolean_value = true;
        end  
    elseif type( boolean_str ) == 'boolean' then
        boolean_value = boolean_str;
    else
        error( 'No boolean value found' );
    end   
    return boolean_value
end


local ignore = function( p_name )
--[[
for _, pattern in ipairs( options['ignore'] or {} ) do
Helper function that escapes all pattern characters so that they will be treated
if mw.ustring.match( p_name, '^' .. pattern .. '$' ) then return true end
as plain text.
end
]]
return false
function str._escapePattern( pattern_str )
end
    return mw.ustring.gsub( pattern_str, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1" );
end


local replace_macros = function( s, param_names )
--[[
local function concat_and_escape( t )
contains_any
local s = table.concat( t, ', ' )
return ( mw.ustring.gsub( s, '%%', '%%%%' ) )
This function returns the first matched element or empty string
Usage:
{{#invoke:String|contains_any|string|search1|search2|search3...}}
Parameters
    1: string
    2...: strings to search within the first string
]]
function str.contains_any( frame )
for i,v in pairs(frame.args) do
if i>1 then
local m=mw.ustring.find( frame.args[1], v, 0, true)
if m then
    return v
    end
end
end
    end
if s and ( type( param_names ) == 'table' ) then
    return
local k_ar, kv_ar = {}, {}
end
for k, v in pairs( param_names ) do
table.insert( k_ar, k )
--[[
table.insert( kv_ar, k .. ': ' .. v)
contains_any_csv
end
s = mw.ustring.gsub( s, 'paramname', concat_and_escape( k_ar ) )  
This function returns the first matched element or empty string.
s = mw.ustring.gsub( s, 'paramandvalue', concat_and_escape( kv_ar ) )
end
Usage:
return s
{{#invoke:String|contains_any_csv|string|search1,search2,search3}}
end
Parameters
    1: string
    2: comma seperated list of strings to search within the first string
]]
function str.contains_any_csv( frame )
for word in mw.ustring.gmatch(frame.args[2], '([^,]+)') do
local m=mw.ustring.find( frame.args[1], word, 0, true)
if m then
    return word
  end
    end
    return
end


local report_params = function( key, param_names )
str.rep = function( frame )
local res = replace_macros( options[key], param_names )
local strval, repval = frame.args[1] or '', tonumber( frame.args[2] )
report = report ..  ( res or '' )
if not repval then return '' end
return res
return string.rep( strval, repval )
end
end


-- no option no work.
str.join = function(frame)
if util.table_empty( options ) then return '' end
local res = {}
 
local sep = ', '
-- get the errors.
for k,v in pairs(frame.args) do
local violations = calculateViolations( frame, options['doc-subpage'] )
if k=='sep' then
-- special request of bora: use skip_empty_numeric
sep = v
if violations['empty-undeclared-numeric'] then  
else
for i = 1, tonumber( options['skip-empty-numeric'] ) or 0 do
if #v>0 then -- avoid empty string
violations['empty-undeclared-numeric'][i] = nil
table.insert(res, v)
end
end
end
end
end
return table.concat( res, sep)
-- handle ignore list, and prune empty violations - in that order!
end
local offenders = 0
for name, tab in pairs( violations ) do
-- remove ignored parameters from all violations
for pname in pairs( tab ) do if ignore( pname ) then tab[pname] = nil end end
-- prune empty violations
if util.table_empty( tab ) then violations[name] = nil end
-- WORK IS DONE. report the errors.
-- if report then count it.
if violations[name] and report_params( name, tab ) then offenders = offenders + 1 end
end


if offenders > 1 then report_params( 'multiple' ) end
str.encode = function(frame)
if offenders ~= 0 then report_params( 'any' ) end -- could have tested for empty( report ), but since we count them anyway...
return mw.text.encode( frame.args[1] or "" )
return wrapReport(report, template_name, options)
end
end


return {
str["קידוד"] = str.encode
['validateparams'] = validateParams,
 
['calculateViolations'] = calculateViolations,
return str
['wrapReport'] = wrapReport
}

גרסה אחרונה מ־01:37, 22 בדצמבר 2021

ניתן ליצור תיעוד על היחידה הזאת בדף יחידה:String/תיעוד

--[[  

This module is intended to provide access to basic string functions.

Most of the functions provided here can be invoked with named parameters, 
unnamed parameters, or a mixture.  If named parameters are used, Mediawiki will 
automatically remove any leading or trailing whitespace from the parameter.  
Depending on the intended use, it may be advantageous to either preserve or
remove such whitespace.

Global options
    ignore_errors: If set to 'true' or 1, any error condition will result in 
        an empty string being returned rather than an error message.  
        
    error_category: If an error occurs, specifies the name of a category to 
        include with the error message.  The default category is  
        [Category:Errors reported by Module String].
        
    no_category: If set to 'true' or 1, no category will be added if an error
        is generated.
        
Unit tests for this module are available at Module:String/tests.
]]

local str = {}

--[[
len

This function returns the length of the target string.

Usage:
{{#invoke:String|len|target_string|}}
OR
{{#invoke:String|len|s=target_string}}

Parameters
    s: The string whose length to report

If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from the target string.  
]]
function str.len( frame )
    local new_args = str._getParameters( frame.args, {'s'} );
    local s = new_args['s'] or '';
    return mw.ustring.len( s )
end

--[[
sub

This function returns a substring of the target string at specified indices.

Usage:
{{#invoke:String|sub|target_string|start_index|end_index}}
OR
{{#invoke:String|sub|s=target_string|i=start_index|j=end_index}}

Parameters
    s: The string to return a subset of
    i: The fist index of the substring to return, defaults to 1.
    j: The last index of the string to return, defaults to the last character.
    
The first character of the string is assigned an index of 1.  If either i or j
is a negative value, it is interpreted the same as selecting a character by 
counting from the end of the string.  Hence, a value of -1 is the same as 
selecting the last character of the string.

If the requested indices are out of range for the given string, an error is 
reported.
]]
function str.sub( frame )
    local new_args = str._getParameters( frame.args, { 's', 'i', 'j' } );
    local s = new_args['s'] or '';
    local i = tonumber( new_args['i'] ) or 1;
    local j = tonumber( new_args['j'] ) or -1;
    
    local len = mw.ustring.len( s );

    -- Convert negatives for range checking
    if i < 0 then
        i = len + i + 1;
    end
    if j < 0 then
        j = len + j + 1;
    end
    
    if i > len or j > len or i < 1 or j < 1 then
        return str._error( 'String subset index out of range' );
    end
    if j < i then
        return str._error( 'String subset indices out of order' );
    end
    
    return mw.ustring.sub( s, i, j )
end

--[[
This function implements that features of {{str sub old}} and is kept in order
to maintain these older templates.
]]
function str.sublength( frame )
    local i = tonumber( frame.args.i ) or 0
    local len = tonumber( frame.args.len )
    return mw.ustring.sub( frame.args.s, i + 1, len and ( i + len ) )
end

--[[
match

This function returns a substring from the source string that matches a 
specified pattern.

Usage:
{{#invoke:String|match|source_string|pattern_string|start_index|match_number|plain_flag|nomatch_output}}
OR
{{#invoke:String|pos|s=source_string|pattern=pattern_string|start=start_index
    |match=match_number|plain=plain_flag|nomatch=nomatch_output}}

Parameters
    s: The string to search
    pattern: The pattern or string to find within the string
    start: The index within the source string to start the search.  The first
        character of the string has index 1.  Defaults to 1.
    match: In some cases it may be possible to make multiple matches on a single 
        string.  This specifies which match to return, where the first match is 
        match= 1.  If a negative number is specified then a match is returned 
        counting from the last match.  Hence match = -1 is the same as requesting
        the last match.  Defaults to 1.
    plain: A flag indicating that the pattern should be understood as plain
        text.  Defaults to false.
    nomatch: If no match is found, output the "nomatch" value rather than an error.

If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from each string.  In some circumstances this is desirable, in 
other cases one may want to preserve the whitespace.

If the match_number or start_index are out of range for the string being queried, then
this function generates an error.  An error is also generated if no match is found.
If one adds the parameter ignore_errors=true, then the error will be suppressed and 
an empty string will be returned on any failure.

For information on constructing Lua patterns, a form of [regular expression], see:

* http://www.lua.org/manual/5.1/manual.html#5.4.1
* http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Patterns
* http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Ustring_patterns

]]
function str.match( frame )
    local new_args = str._getParameters( frame.args, {'s', 'pattern', 'start', 'match', 'plain', 'nomatch'} );
    local s = new_args['s'] or '';
    local start = tonumber( new_args['start'] ) or 1;
    local plain_flag = str._getBoolean( new_args['plain'] or false );
    local pattern = new_args['pattern'] or '';
    local match_index = math.floor( tonumber(new_args['match']) or 1 );
    local nomatch = new_args['nomatch'];
    
    if s == '' then
        return str._error( 'Target string is empty' );
    end
    if pattern == '' then
        return str._error( 'Pattern string is empty' );
    end
    if math.abs(start) < 1 or math.abs(start) > mw.ustring.len( s ) then
        return str._error( 'Requested start is out of range' );
    end
    if match_index == 0 then
        return str._error( 'Match index is out of range' );
    end
    if plain_flag then
        pattern = str._escapePattern( pattern );
    end
    
    local result
    if match_index == 1 then
        -- Find first match is simple case
        result = mw.ustring.match( s, pattern, start )
    else
        if start > 1 then
            s = mw.ustring.sub( s, start );
        end
        
        local iterator = mw.ustring.gmatch(s, pattern);
        if match_index > 0 then
            -- Forward search
            for w in iterator do
                match_index = match_index - 1;
                if match_index == 0 then
                    result = w;
                    break;
                end
            end    
        else
            -- Reverse search
            local result_table = {};
            local count = 1;
            for w in iterator do
                result_table[count] = w;
                count = count + 1;
            end
            
            result = result_table[ count + match_index ];            
        end
    end        
    
    if result == nil then
        if nomatch == nil then
            return str._error( 'Match not found' );
        else
            return nomatch;
        end
    else
        return result;
    end
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 str._error( 'String index out of range' );
    end    
    
    return mw.ustring.sub( target_str, pos, pos );
end

--[[
str_find

This function duplicates the behavior of {{str_find}}, including all of its quirks.
This is provided in order to support existing templates, but is NOT RECOMMENDED for 
new code and templates.  New code is recommended to use the "find" function instead.

Returns the first index in "source" that is a match to "target".  Indexing is 1-based,
and the function returns -1 if the "target" string is not present in "source".

Important Note: If the "target" string is empty / missing, this function returns a
value of "1", which is generally unexpected behavior, and must be accounted for
separatetly.
]]
function str.str_find( frame )
    local new_args = str._getParameters( frame.args, {'source', 'target'} );
    local source_str = new_args['source'] or '';
    local target_str = new_args['target'] or '';

    if target_str == '' then
        return 1;
    end    
    
    local start = mw.ustring.find( source_str, target_str, 1, true )
    if start == nil then
        start = -1
    end
    
    return start
end

--[[
find

This function allows one to search for a target string or pattern within another
string.

Usage:
{{#invoke:String|find|source_str|target_string|start_index|plain_flag}}
OR
{{#invoke:String|find|source=source_str|target=target_str|start=start_index|plain=plain_flag}}

Parameters
    source: The string to search
    target: The string or pattern to find within source
    start: The index within the source string to start the search, defaults to 1
    plain: Boolean flag indicating that target should be understood as plain
        text and not as a Lua style regular expression, defaults to true

If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from the parameter.  In some circumstances this is desirable, in 
other cases one may want to preserve the whitespace.

This function returns the first index >= "start" where "target" can be found 
within "source".  Indices are 1-based.  If "target" is not found, then this 
function returns 0.  If either "source" or "target" are missing / empty, this
function also returns 0.

This function should be safe for UTF-8 strings.
]]
function str.find( frame )
    local new_args = str._getParameters( frame.args, {'source', 'target', 'start', 'plain' } ); 
    local source_str = new_args['source'] or '';
    local pattern = new_args['target'] or '';
    local start_pos = tonumber(new_args['start']) or 1;
    local plain = new_args['plain'] or true;
        
    if source_str == '' or pattern == '' then
        return 0;
    end    
    
    plain = str._getBoolean( plain );

    local start = mw.ustring.find( source_str, pattern, start_pos, plain )
    if start == nil then
        start = 0
    end
    
    return start
end

--[[
replace

This function allows one to replace a target string or pattern within another
string.

Usage:
{{#invoke:String|replace|source_str|pattern_string|replace_string|replacement_count|plain_flag}}
OR
{{#invoke:String|replace|source=source_string|pattern=pattern_string|replace=replace_string|
   count=replacement_count|plain=plain_flag}}

Parameters
    source: The string to search
    pattern: The string or pattern to find within source
    replace: The replacement text
    count: The number of occurences to replace, defaults to all.
    plain: Boolean flag indicating that pattern should be understood as plain
        text and not as a Lua style regular expression, defaults to true 
]]
function str.replace( frame )
    local new_args = str._getParameters( frame.args, {'source', 'pattern', 'replace', 'count', 'plain' } ); 
    local source_str = new_args['source'] or '';
    local pattern = new_args['pattern'] or '';
    local replace = new_args['replace'] or '';
    local count = tonumber( new_args['count'] );
    local plain = new_args['plain'] or true;
        
    if source_str == '' or pattern == '' then
        return source_str;
    end    
    plain = str._getBoolean( plain );

    if plain then
        pattern = str._escapePattern( pattern );
        replace = mw.ustring.gsub( replace, "%%", "%%%%" ); --Only need to escape replacement sequences.
    end
    
    local result;

    if count ~= nil then
        result = mw.ustring.gsub( source_str, pattern, replace, count );
    else
        result = mw.ustring.gsub( source_str, pattern, replace );
    end        

    return result;
end

--[[
"Reverse" reverses a string, a'la string.reverse()
]]
str.reverse = function( frame )
    local tab = mw.text.split( frame.args[1] or '', '' )
    local restab = {}
    for i = #tab, 1, -1 do table.insert( restab, tab[i] ) end
    return table.concat( restab )
end

str['היפוך'] = str.reverse

--[[
Helper function that populates the argument list given that user may need to use a mix of
named and unnamed parameters.  This is relevant because named parameters are not
identical to unnamed parameters due to string trimming, and when dealing with strings
we sometimes want to either preserve or remove that whitespace depending on the application.
]]
function str._getParameters( frame_args, arg_list )
    local new_args = {};
    local index = 1;
    local value;
    
    for i,arg in ipairs( arg_list ) do
        value = frame_args[arg]
        if value == nil then
            value = frame_args[index];
            index = index + 1;
        end
        new_args[arg] = value;
    end
    
    return new_args;
end        

--[[
Helper function to handle error messages.
]]
function str._error( error_str )
    local frame = mw.getCurrentFrame();
    local error_category = frame.args.error_category or 'שגיאות טיפול במחרוזת';
    local ignore_errors = frame.args.ignore_errors or false;
    local no_category = frame.args.no_category or false;
    
    if str._getBoolean(ignore_errors) then
        return '';
    end
    
    local error_str = '<strong class="error">String Module Error: ' .. error_str .. '</strong>';
    if error_category ~= '' and not str._getBoolean( no_category ) then
    	if mw.title.getCurrentTitle().namespace ~= 10 then
        	error_str = '[[Category:' .. error_category .. ']]' .. error_str;
        end
    end        
    
    return error_str;
end

--[[
Helper Function to interpret boolean strings
]]
function str._getBoolean( boolean_str )
    local boolean_value;
    
    if type( boolean_str ) == 'string' then
        boolean_str = boolean_str:lower();
        if boolean_str == 'false' or boolean_str == 'no' or boolean_str == '0' 
                or boolean_str == '' then
            boolean_value = false;
        else
            boolean_value = true;
        end    
    elseif type( boolean_str ) == 'boolean' then
        boolean_value = boolean_str;
    else
        error( 'No boolean value found' );
    end    
    return boolean_value
end

--[[
Helper function that escapes all pattern characters so that they will be treated 
as plain text.
]]
function str._escapePattern( pattern_str )
    return mw.ustring.gsub( pattern_str, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1" );
end

--[[
contains_any
 
This function returns the first matched element or empty string
 
Usage:
{{#invoke:String|contains_any|string|search1|search2|search3...}}
 
Parameters
    1: string
    2...: strings to search within the first string
]]
function str.contains_any( frame )
	for i,v in pairs(frame.args) do
		if i>1 then
			local m=mw.ustring.find( frame.args[1], v, 0, true)
			if m then
	    		return v
    		end
		end
    end
    return
end
 
 --[[
contains_any_csv
 
This function returns the first matched element or empty string.
 
Usage:
{{#invoke:String|contains_any_csv|string|search1,search2,search3}}
 
Parameters
    1: string
    2: comma seperated list of strings to search within the first string
]]
function str.contains_any_csv( frame )
	for word in mw.ustring.gmatch(frame.args[2], '([^,]+)') do
		local m=mw.ustring.find( frame.args[1], word, 0, true)
		if m then
    		return word
   		end
    end
    return
end

str.rep = function( frame )
	local strval, repval = frame.args[1] or '', tonumber( frame.args[2] )
	if not repval then return '' end
	return string.rep( strval, repval )
end

str.join = function(frame)
	local res = {}
	local sep = ', '
	for k,v in pairs(frame.args) do
		if k=='sep' then
			sep = v
		else
			if #v>0 then -- avoid empty string
				table.insert(res, v)
			end
		end
	end
	return table.concat( res, sep)
end

str.encode = function(frame)
	return mw.text.encode( frame.args[1] or "" )
end

str["קידוד"] = str.encode

return str