Module:Error

From Zoophilia Wiki
Revision as of 11:49, 4 April 2013 by meta>Mr. Stradivarius (simplify code some more and trim whitespace from the message)
Jump to navigationJump to search

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

-- This module implements {{error}}.

local p = {}

local HtmlBuilder = require('Module:HtmlBuilder')

local function _error(args)
    local message = args.message or args[1] or error('no message specified', 2)
    message = mw.ustring.match(tostring(message), '^%s*(.*%S)') or ''  -- Convert message to string and trim whitespace.
    local tag = mw.ustring.lower(tostring(args.tag))

    -- Work out what html tag we should use.
    if not (tag == 'p' or tag == 'span' or tag == 'div') then
        tag = 'strong'
    end

    -- Generate the html.
    local root = HtmlBuilder.create(tag)
    root
        .addClass('error')
        .wikitext(message)

    return tostring(root)
end

function p.error(frame)
    local origArgs
    if frame == mw.getCurrentFrame() then
        -- We're being called via #invoke. The args are passed through to the module
        -- from the template page, so use the args that were passed into the template.
        origArgs = frame.args
    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 whitespace to be false, so to preserve the previous 
    -- behavior of the template, change any arguments consisting only of whitespace
    -- to nil, so Lua will consider them false too.
    local args = {}
    for k, v in pairs(origArgs) do
        if mw.ustring.match(v, '%S') then
            args[k] = v
        end
    end

    return _error(args)
end

return p