Module:Utils

From Team Fortress Wiki
Jump to: navigation, search

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

local util = {}

function util.get_args(frame)
    local origArgs
    if frame == mw.getCurrentFrame() then
        -- We're being called via #invoke. If the invoking template passed any args, use
        -- them. Otherwise, use the args that were passed into the template.
        origArgs = frame:getParent().args
        for k, v in pairs(frame.args) do
            origArgs = frame.args
            break
        end
    else
        -- We're being called from another module or from the debug console, so assume
        -- the args are passed in directly.
        origArgs = frame
    end
 
    -- ParserFunctions considers the empty string to be false, so to preserve the previous 
    -- behavior of the template, change any empty arguments to nil, so Lua will consider
    -- them false too.
    local args = {}
    for k, v in pairs(origArgs) do
        if v ~= '' then
            -- parameter names should be case-insensitive
            if type(k) == 'string' then
                k = string.lower(k)
            end
            args[k] = v
        end
    end
    return args
end

function util.expandWikitext(wikitext)
    -- function to process wikitext, expanding templates, and return result
    return mw.getCurrentFrame():preprocess(wikitext)
end

function util.processArg(arg, default)
    -- function that replicates wiki template behaviour where nil and blank arguments are equivalent here
    if arg and arg ~= '' then
        return arg
    end
    return default or ''
end

function util.processArgLowered(arg, default)
    -- similar to processArg but returns lowered string
    local processed_arg = util.processArg(arg, default)
    if processed_arg then
        return string.lower(processed_arg)
    end
    return ''
end

return util