Moduł:Narzędzia licencyjne

Z Nonsensopedii, polskiej encyklopedii humoru
Wersja z dnia 11:00, 10 cze 2020 autorstwa Eksekk (dyskusja • edycje) (nowa strona)
(różn.) ← przejdź do poprzedniej wersji • przejdź do aktualnej wersji (różn.) • przejdź do następnej wersji → (różn.)

local p = {}

function p.makeTemplate(name, args, runFunction)
    local code = "<nowiki>{{"
    if runFunction ~= nil then
        -- invoke module
        code = code .. "#invoke:" .. name .. "|" .. runFunction
    else
        -- template
        code = code .. name .. "|"
    end
    for name, value in pairs(args) do
        code = code .. "|" .. name .. "=" .. value
    end
    return "" .. code .. "}}</nowiki>"
end

-- returns name, value from parameter of form abc=def or nil and parameter if name is null
function p.parseParameter(param)
    local equalsPos = param:find("=", 1, true)
    if equalsPos == nil then
        return nil, param
    else
        return param:sub(1, equalsPos - 1), param:sub(equalsPos + 1)
    end
end

-- returns template name, table with arguments
function p.stripTemplate(string)
    local arguments = {}
    
    local startingBracePos, endingBracePos = string:find("\{\{.*\}\}")
    if startingBracePos == nil or endingBracePos == nil then
        return nil, nil
    end
    
    local templateNameBegin, templateNameEnd = string:find("%w+", startingBracePos + 2)
    local templateName = string:sub(templateNameBegin, templateNameEnd)
    
    local i = templateNameEnd + 2
    local begins = 0
    local argumentString = ""
    local unnamedParameterCounter = 1
    while i < endingBracePos - 1 do
        if string:sub(i, i) == "{" and string:sub(i + 1, i + 1) == "{" then
            begins = begins + 1
        elseif string:sub(i, i) == "}" and string:sub(i + 1, i + 1) == "}" then
            begins = begins - 1
        elseif string:sub(i, i) == "|" and begins == 0 then -- not | inside other template
            -- get argument
            local name, value = parseParameter(argumentString)
            if name == nil then
                name = unnamedParameterCounter
                unnamedParameterCounter = unnamedParameterCounter + 1
            end
            arguments[name] = value
            argumentString = ""
        end
        if not (string:sub(i, i) == "|" and begins == 0) then
            argumentString = argumentString .. string:sub(i, i)
        end
        i = i + 1
    end
    if argumentString ~= "" then
        local name, value = parseParameter(argumentString)
        if name == nil then
            name = unnamedParameterCounter
        end
        arguments[name] = value
    end
    return templateName, arguments
end
-- {{domniemanie|{{self|{{PD}}}}}}
-- {{name|param|param2=test|{{test2}}}}
-- {{test|{{test2|{{test3}}}}}}
-- {{test|{{test2|a}}|{{test3|b}}}}

return p