Module:PageVars
Description
This module calculates one or more expressions and substitutes the results into a single block of wikitext.
Its primary purpose is to avoid repeating the same `` calculation multiple times on a page. It calculates all values once and allows them to be reused in the provided text. This is a safe, stateless alternative to the Variable extensions that works correctly with the future Parsoid MediaWiki parser.
Usage
The module has one function: calculateAndDisplay. It is called with the following structure:
{{#invoke:PageVars|calculateAndDisplay
| name1 = formula1
| name2 = formula2
| ...
| display = Wikitext using $name1$ and $name2$...
}}
Parameters
display: (Required) A block of wikitext that will be displayed. This text can contain placeholders that correspond to the names of the formulas.name1,name2, etc.: (Required) User-defined names for the variables.- The name is used for the placeholder (e.g.,
prob_Abecomes$prob_A$). - The value is the formula to be calculated by the
parser function (e.g.,3 / 13 round 4).
- The name is used for the placeholder (e.g.,
Example
This example calculates two different probabilities and uses them in two separate paragraphs within a single call.
Code
{{#invoke:PageVars|calculateAndDisplay
| prob_A = 3 / 13 round 4
| prob_B = 1 / 7 round 4
| display =
The probability of event A is '''$prob_A$'''.
The probability of event B is '''$prob_B$'''.
We can then compare $prob_A$ and $prob_B$ to determine the likely outcome based on these two independent calculations. All values were calculated in a single, efficient operation.
}}
Result
The probability of event A is 0.2308.
The probability of event B is 0.1429.
We can then compare 0.2308 and 0.1429 to determine the likely outcome based on these two independent calculations. All values were calculated in a single, efficient operation.
-- Module:PageVars
-- Calculates multiple named expressions and substitutes them into a display block.
-- See /doc subpage for documentation.
local p = {}
function p.calculateAndDisplay(frame)
local args = frame.args
local displayText = args.display or ''
local results = {}
for key, formula in pairs(args) do
if key ~= 'display' and type(formula) == 'string' and formula ~= '' then
results[key] = frame:preprocess( '{{#expr: ' .. formula .. '}}' )
end
end
for key, value in pairs(results) do
local placeholder = '%$' .. key .. '%$' -- %$ to match a literal $
displayText = mw.ustring.gsub(displayText, placeholder, value)
end
return frame:preprocess(displayText)
end
return p