Module:Medals table country
Appearance
![]() | This module is rated as ready for general use. It has reached a mature form and is thought to be relatively bug-free and ready for use wherever appropriate. It is ready to mention on help pages and other Wikipedia resources as an option for new users to learn. To reduce server load and bad output, it should be improved by sandbox testing rather than repeated trial-and-error editing. |
implements:
Usage
-- 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