Module:Johnuniq/Testargs

From Wikipedia

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

-- Does argumentPairs return arguments in the exact order in the template?
-- Probably, but if we stick them in a table, I suspect that order is lost?
-- That matters for {{convert}} with its "adj" argument.

local p = {}
local format = string.format

local abvs = {
    -- Abbreviations for types.
    ['nil']      = '!',
    ['number']   = 'n',
    ['string']   = 's',
    ['boolean']  = 'b',
    ['table']    = 't',
    ['function'] = 'f',
    ['thread']   = 'p',
    ['userdata'] = 'u',
}

local function abvtype(var)
    return abvs[type(var)] or '?'
end

local function insert(results, k, v)
    local types = '[' .. abvtype(k) .. abvtype(v) .. ']'
    local key = '[' .. tostring(k) .. ']'
    local val = '[' .. tostring(v) .. ']'
    table.insert(results, format('%6s  %-8s  %s', types, key, val))
end

local function show(results, frame, name, keys)
    -- Append arguments from frame into results.
    table.insert(results, name)
    local start = #results
    if keys then
        for _, v in ipairs(keys) do
            insert(results, v, frame.args[v])
        end
    else
        for k, v in pairs(frame.args) do
            insert(results, k, v)
        end
    end
    if #results == start then
        table.insert(results, '  (no arguments)')
    end
end

function p.main(frame)
    local pframe = frame:getParent()
    local undefined = { 'zilch', '' }
    local results = {}
    table.insert(results, '<pre>')
    show(results, frame, 'Frame (arguments from module #invoke)')
    show(results, frame, 'Frame undefined arguments', undefined)
    show(results, pframe, 'Parent (arguments passed to template)')
    show(results, pframe, 'Parent undefined arguments', undefined)
    table.insert(results, '</pre>')
    return table.concat(results, '\n')
end

return p