Module:String

From Space Exploration
Jump to navigation Jump to search

Documentation for this module may be created at Module:String/doc

-- This module has been copied from: https://dev.fandom.com/wiki/Module:String
-- It is available under: "Except where otherwise permitted, the text on Fandom communities (known as “wikis”) is licensed under the
-- Creative Commons Attribution-Share Alike License 3.0 (Unported) (CC BY-SA)."

-- license: https://www.fandom.com/licensing

--- Return delimited string piece, like PHP's `explode()`.
--  Indexing is **0-based** to match the behavior of `{{#explode}}`
--  parser function.
--  
--  @function           str.explode
--  @param              {table} frame Invocation frame object.
--  @param              {table} frame.args Invocation/template arguments.
--  @param              {string} frame.args.source Delimited string to split.
--  @param              {string} frame.args.dlm Symbol or character to split
--                      with.
--  @param[opt]         {string} frame.args.pos Initial piece position.
--                      Default: `0`.
--  @param[opt]         {string} frame.args.lim Maximum number of pieces to
--                      append. Default: `1`.
--  @return             {string} Percent-encoded string.
--  @usage
--     
--     {{string|explode|source string|delimiter|position 0-index|piece limit}}
--     
--  @usage
--     
--     {{string|explode
--     | source = source string
--     | dlm = delimiter
--     | pos = position 0-index
--     | lim = piece limit
--     }}
--  
local str = {}
local ustring, text = mw.ustring, mw.text
   
function str.explode( frame )
    local args = str._getParameters( frame.args, { 'source', 'dlm', 'pos', 'lim' } )
    local source = args['source'] or ''
    local delim = str._escapePattern( args['dlm'] or ' ' )
    local pos = ( tonumber( args['pos'] or '0' ) + 1 )
    local pieces = text.split(source, delim)
    local limit = tonumber( args['lim'] ) or #pieces
    local dividers = {}
    for div in ustring.gmatch(source, delim) do
        table.insert(dividers, div)
    end
    if limit < #pieces then
        for index, value in ipairs(pieces) do
            if index > limit then
                pieces[limit] = pieces[limit] .. dividers[index-1] .. value
            end
        end
        for index, value in ipairs(pieces) do
            if index > limit then pieces[index] = nil end
        end
    end
    if pos < 1 then
        pos = #pieces + pos
    end
    return pieces[pos] or ''
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


--[[
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 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


--[[
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

--quick tester function
function str.testing()
return 'hello'
end

return str