Module:InfoboxExtractor

From JoJo's Bizarre Encyclopedia - JoJo Wiki
Revision as of 13:23, 1 May 2023 by Vish (talk | contribs)
Jump to navigation Jump to search

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

local p = {}

local function extractInfobox(wikitext)
    local startInfobox = string.find(wikitext, "{{[^}]*Infobox")
    if not startInfobox then
        return nil
    end

    local braceCount = 0
    local endInfobox = startInfobox

    for i = startInfobox, #wikitext do
        local char = wikitext:sub(i, i)
        if char == '{' then
            braceCount = braceCount + 1
        elseif char == '}' then
            braceCount = braceCount - 1
        end

        if braceCount == 0 then
            endInfobox = i
            break
        end
    end

    return wikitext:sub(startInfobox, endInfobox)
end

local function getLabelValue(infobox, label)
    local pattern = "|" .. label .. " *= *([^\n|]+)"
    local iterator = string.gmatch(infobox, pattern)
    local value = nil
    local previousMatchEnd = 0

    for match in iterator do
        local matchStart, matchEnd = string.find(infobox, pattern, previousMatchEnd)

        local nestedTemplatesCount = 0
        for i = previousMatchEnd + 1, matchStart - 1 do
            local char = infobox:sub(i, i)
            if char == '{' then
                nestedTemplatesCount = nestedTemplatesCount + 1
            elseif char == '}' then
                nestedTemplatesCount = nestedTemplatesCount - 1
            end
        end

        if nestedTemplatesCount == 0 then
            value = match
            break
        else
            previousMatchEnd = matchEnd
        end
    end

    return value
end

function p.extract(frame)
    local pageTitle = frame.args[1]
    if not pageTitle then
        return "Error: Please provide a page title."
    end

    local page = mw.title.new(pageTitle)
    if not page or not page.exists then
        return "Error: Page not found."
    end

    local wikitext = page:getContent()
    local infobox = extractInfobox(wikitext)

    if not infobox then
        return "Error: Infobox not found."
    end

    local label = frame.args[2]
    if not label then
        return "Error: Please provide a label."
    end

    local value = getLabelValue(infobox, label)

    if not value then
        return "Error: Label not found in infobox."
    end

    return value
end

return p