Module:File

From Space Station 14 Wiki
Module documentation
View or edit this documentation (about module documentation)

Implements {{File}}.


local p = {}
local getArgs = require('Module:Arguments').getArgs

-- =====================

-- Given a table with positional and/or named fields,
-- generates a new table where each field is a positional one, 
-- while also turning named fields into `key=value` values.
-- 
-- If a field was positional, it remains as is.
-- If a field was named, its key and value are combined in `key=value` format and appended to the end.
-- 
-- The purpose of this function is to parse arbitrary arguments from a template 
-- and turn them into strings that can be used as parameters to things like `[[File]]` in an arbitrary wikitext.
local function extracts_args_to_strings(args)
    local res = { }
    -- first handle positional args
    for _, value in ipairs(args) do
        table.insert(res, value)
    end

    -- then named ones
    for key, value in pairs(args) do
        if type(key) ~= "number" then
            table.insert(res, key .. '=' .. value)
        end
    end

    return res
end

-- =====================

function p.main(frame)
    local args = getArgs(frame)
    
    frame = mw.getCurrentFrame()

    local filename = args[1]
    if filename == nil then
        error("failed to generate image: filename not provided")
    end

    local args_str = table.concat(extracts_args_to_strings(args), '|')

    return frame:preprocess("[[File:" .. args[1] .. "|" .. args_str .. "]]")
end

return p