Module:Get cell
Appearance
-- This module serves to calculate a table cell out of the values of other cells
-- Documentation: https://en.wikipedia.org/wiki/Module:Calculated_cell
-- Authors: Sophivorus
-- License: GNU General Public License 3 or later (http://www.gnu.org/licenses/gpl-3.0.html)
local CalculatedCell = {}
local WikitextParser = require( 'Module:WikitextParser' )
local function getError( key )
local messages = {
['no-table-id'] = 'No table id given',
['page-not-found'] = 'Page not found',
['table-not-found'] = 'Table not found'
}
local frame = mw.getCurrentFrame()
local message = frame.args[ key ] or messages[ key ]
return mw.html.create( 'span' ):addClass( 'error' ):wikitext( message )
end
function CalculatedCell.main( frame )
-- Get the template parameters
local params = frame:getParent().args
-- Get the page wikitext
local pageTitle = mw.title.getCurrentTitle()
local page = params[3]
if page then
pageTitle = mw.title.new( page )
end
if not pageTitle then
return getError( 'page-not-found' )
end
local pageWikitext = pageTitle:getContent()
-- Get the table data
local tableId = params[2]
if not tableId then
return getError( 'no-table-id' )
end
local tableWikitext = WikitextParser.getTableById( pageWikitext, tableId )
local tableData = WikitextParser.getTableData( tableWikitext )
-- Replace any placeholders (A1, B2, etc) in the given expression for the real values
local expression = params[1]
if not expression then
return
end
local lang = mw.language.getContentLanguage()
local rowLetter, rowNumber, rowData, cellNumber, cellValue
for placeholder in string.gmatch( expression, '[A-Z]+[0-9]+' ) do
rowLetter = string.match( placeholder, '[A-Z]+' )
rowNumber = string.find( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', rowLetter )
rowData = tableData[ rowNumber ]
cellNumber = tonumber( string.match( placeholder, '[0-9]+' ) )
cellValue = rowData[ cellNumber ]
cellValue = lang:parseFormattedNumber( cellValue )
expression = string.gsub( expression, placeholder, cellValue )
end
return frame:callParserFunction( '#expr', expression )
end
return CalculatedCell