Module:UtilHyper

From Heroes of Might and Magic: Olden Era Official Wiki

This module takes a text and a hyper list of pattern = url and returns a text where words that match the pattern will have become hyperlinks.

Usage

Input:

{{#invoke:UtilHyper|apply
| text = While worn, grants all unlearned Subskills of the following Skills: Defense, Primal Magic, Recruitment
| hyper =
    Defense=Defense
    Primal [Mm]agic=Primal_Magic/fr;
    Rec.*nt=Recruitment
}}

Output: While worn, grants all unlearned Subskills of the following Skills: Defense, Primal Magic, Recruitment


-- Usage: see Module:UtilHyper/doc
local p = {}

-- Displays a variable
------------------------------------------------------------------------------------------------------------------------
local function dump(target)
    return '<pre>' .. mw.dumpObject(target) .. '</pre>'
end

------------------------------------------------------------------------------------------------------------------------
local function lowerPattern(pattern)
    return (mw.ustring.gsub(pattern, "%a", function(c)
        local lower, upper = mw.ustring.lower(c), mw.ustring.upper(c)
        if lower ~= upper then
            return "[" .. lower .. upper .. "]"
        end
        return c
    end))
end

------------------------------------------------------------------------------------------------------------------------
local function parseHyper(hyper)
    local output = {}
    if not hyper or type(hyper) ~= 'string' then
        return output
    end
    for line in hyper:gmatch("[^\n;]+") do
        local key, value = line:match("^([^=]+)=(.*)$")
        if key and value then
            key = mw.text.trim(key)
            value = mw.text.trim(value)
            if key ~= "" then
                value = value == '' and key or value
                --key = '(' .. lowerPattern(key) .. ')'
                key = '(' .. key .. ')'
                output[key] = value
            end
        end
    end
    return output
end

-- Main processing function
------------------------------------------------------------------------------------------------------------------------
local function process(text, hyper)
    if not text or type(text) ~= 'string' then
        return text
    end

    local hub = parseHyper(hyper)
    for pattern, value in pairs(hub) do
        text = mw.ustring.gsub(text, pattern, '[[' .. value .. '|%1]]', 1)
    end

    return text
end

-- M A I N
------------------------------------------------------------------------------------------------------------------------
function p.apply(frame, hyper)
    if frame and frame.args then
        local args = frame.args
        local text = args.text or args[1] or ''
        hyper = args.hyper or args[2] or hyper or ''
        return process(text, hyper)
    else
        return process(frame, hyper)
    end
end

return p