Module:TextReplacer

From Akurasu Wiki
Jump to navigationJump to search

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

--[[
    Module:Example

    This module provides a function to perform text replacements on a specified page
    using a template replacement table defined in a separate page.

    Usage: {{#invoke:Example|main|BasicPage=OriginalPage|ReplaceList=ReplacementsTable}}

    Parameters:
    - BasicPage: The name of the page on which the text replacements should be performed.
    - ReplaceList: The name of the page containing the replacement table.

    Replacement Table Format:
    The replacement table should be defined in the following format:
    `Key1`||Replacement1;
    `Key2`||Replacement2;
    ...

    - Each line represents a single replacement entry.
    - The key and replacement value are separated by "||".
    - The key should be enclosed in backticks (`).
    - The replacement value can contain wikitext formatting.
    - Each line should end with a semicolon (;).
    - Empty lines are ignored.

    Example Replacement Table:
    `A`||'''Apple''';
    `B`||''Banana'';
    `C`||Carrot;
]]

local p = {}

function p.main(frame)
    local args = frame.args
    local BasicPage = frame.args['BasicPage']
    local ReplaceList = frame.args['ReplaceList']

    if not BasicPage then
        return "Error: BasicPage parameter is missing."
    end

    if not ReplaceList then
        return "Error: ReplaceList parameter is missing."
    end

    local replaceTable = {}
    local replaceContent = frame:expandTemplate{title = ReplaceList}
    for line in replaceContent:gmatch("[^\n]+") do
        local key, value = line:match("(`[^`]+`)||([^;]+)")
        if key and value then
            key = mw.text.trim(key)
            value = mw.text.trim(value)
            replaceTable[key] = value
        end
    end

    local page = mw.title.new(BasicPage)
    if page then
        local pageContent = page:getContent()
        if pageContent then
            -- Perform text replacements based on replaceTable
            for key, value in pairs(replaceTable) do
                pageContent = pageContent:gsub(key, value)
            end
            return pageContent
        else
            return "Page " .. BasicPage .. " exists but has no content."
        end
    else
        return "Page " .. BasicPage .. " does not exist."
    end
end

return p