Jump to content

Module:Medals table country

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Miria~01 (talk | contribs) at 15:58, 9 September 2023 (codetest). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

-- Module for calculating the sum of specified columns in a named wikitext table
local p = {}

function p.calculateSum(frame)
    local args = frame.args
    local tableName = args[1] or ""  -- ID of the targeted table
    local columnList = args[2] or "" -- List of columns to calculate sums for (e.g., "1,2,3,4")

    -- Split the column list into individual column numbers
    local columns = {}
    for column in mw.text.gsplit(columnList, ",") do
        local colNum = tonumber(column)
        if colNum then
            table.insert(columns, colNum)
        end
    end

    -- Find the wikitext table by ID
    local wikitext = mw.text.unstrip(frame:preprocess('{{#' .. tableName .. '}}'))

    if not wikitext then
        return "Table not found"
    end

    -- Initialize sums to 0 for each column
    local sums = {}
    for _, colNum in ipairs(columns) do
        sums[colNum] = 0
    end

    -- Split the wikitext into rows
    local rows = mw.text.split(wikitext, "\n")

    -- Iterate through rows and specified columns to calculate the sums
    for _, row in ipairs(rows) do
        local cells = mw.text.split(row, "|")
        for _, colNum in ipairs(columns) do
            local cell = cells[colNum] or ""
            local value = tonumber(string.match(mw.text.trim(cell), "%d+")) or 0
            sums[colNum] = sums[colNum] + value
        end
    end

    -- Generate wikitable syntax with separate cells for each sum
    local sumString = ""
    for _, colNum in ipairs(columns) do
        sumString = sumString .. sums[colNum] .. " || "
    end
    sumString = mw.ustring.sub(sumString, 1, -5)  -- Remove the trailing " || " at the end

    return sumString
end

return p