Module:Template input parse: Difference between revisions

Ganaram inukshuk (talk | contribs)
Added variant function that returns split numeric values
Ganaram inukshuk (talk | contribs)
Added functions to parse numeric pairs
Line 48: Line 48:
return nil
return nil
end
end
end
-- Helper function
-- Parses a pair of numeric values
function p.parse_numeric_pair(unparsed, delimiter)
local parsed = {}
local delimiter = delimiter or ':'
local expr = '([^' .. delimiter .. ']+)'
for entry in string.gmatch(unparsed, expr) do
local trimmed = entry:gsub("^%s*(.-)%s*$", "%1")
local numeric = tonumber(trimmed)
table.insert(parsed, numeric) -- Add to array
end
if #parsed == 2 then
return parsed
else
return nil
end
end
-- Helper function
-- Parses a list of numeric pairs
-- Delimiter between each pair must be a semicolon
-- Delimiter between the pair's two values can be anything; default is slash
-- as the intended use is parsing ratios a/b
function p.parse_numeric_pairs(unparsed, delimiter)
local delimiter = delimiter or "/"
-- Split the string of unparsed pairs
local parsed = p.parse_entries(unparsed)
-- Then tokenize the tokens into numeric pairs
local pairs_ = {}
for i = 1, #parsed do
local pair = p.parse_numeric_pair(parsed[i], delimiter)
if pair ~= nil and #pair == 2 then
table.insert(pair)
end
end
return pairs_
end
end