Module:Sandbox/User:Ahecht/Inflation
Appearance
Implements {{Inflation/year}}
local p={}
local function split(text, pattern, plain)
local ret = {}
local s, l = 1, string.len( text )
while s do
local e, n = string.find( text, pattern, s, plain )
if not e then
table.insert(ret, string.sub ( text, s ))
s = nil
elseif n < e then
-- Empty separator!
table.insert(ret, string.sub ( text, s, e ))
if e < l then
s = e + 1
else
s = nil
end
else
table.insert(ret, e > s and string.sub( text, s, e - 1 ) or '')
s = n + 1
end
end
return ret
end
function p._parse(index, template, frame)
if not frame then frame = mw.getCurrentFrame() end
local error = ' when using {{tl|Inflation/' .. template .. '}}.{{main other|[[Category:Pages with errors in inflation template]]}}</span>'
if index and index ~= 'ERR' then
local tempTitle = "Inflation/" .. index .. "/dataset"
local dataset = mw.title.new(tempTitle, "Template"):getContent()
if dataset then
local redirect = mw.ustring.match(dataset, "#REDIRECT%s*%[%[Template:Inflation/(.*)/dataset%]%]")
if redirect then return p._parse(redirect, template, frame) end
dataset = mw.ustring.gsub(mw.ustring.gsub(dataset, "<!%-%-.-%-%->", ""), "\n?%s*|%s*#default%s*", "")
local datatable = {}
local data = split(dataset, "\n", true)
for _, row in ipairs(data) do
local year, value = mw.ustring.match(row, "%s*|%s*(%d%d%d%d)%s*=%s*([^=]+)%s*")
if year and value and tonumber(year) then
year = tonumber(year)
if tonumber(value) then
datatable[year] = tonumber(value)
elseif mw.ustring.sub(value,1,8) == '{{#expr:' and mw.ustring.sub(value,-2) == '}}' then
value = mw.ustring.sub(value, 3, -3)
datatable[year] = tonumber(frame:callParserFunction( value ))
end
end
end
if table.maxn(datatable) > 0 then
return datatable
else
error = '<span class="error">Error: unable to parse "Template:' .. tempTitle .. '"' .. error
end
else
error = '<span class="error">Error: undefined index "' .. index .. '"' .. error
end
else
error = '<span class="error">Error: no index specified' .. error
end
return frame:preprocess(error)
end
function p.year(frame)
local index = frame.args.index or frame.args[1] or frame:getParent().args.index or frame:getParent().args[1]
local result = p._parse(index, 'year', frame)
if type(result) == "table" then
return table.maxn(result)
else
return result
end
end
return p