Difference between revisions of "Module:TableTools"
Jump to navigation
Jump to search
add p.numData function
>Mr. Stradivarius (sparseIpairs: return nil explicitly if i > lim) |
>Mr. Stradivarius (add p.numData function) |
||
Line 147: | Line 147: | ||
table.sort(nums) | table.sort(nums) | ||
return nums | return nums | ||
end | |||
--[[ | |||
------------------------------------------------------------------------------------ | |||
-- numData | |||
-- | |||
-- Given a table with keys like ("foo1", "bar1", "foo2", "baz2"), returns a table | |||
-- of subtables in the format | |||
-- { [1] = {foo = 'text', bar = 'text'}, [2] = {foo = 'text', baz = 'text'} } | |||
-- Keys that don't end with an integer are stored in a subtable named "other". | |||
-- The compress option compresses the table so that it can be iterated over with | |||
-- ipairs. | |||
------------------------------------------------------------------------------------ | |||
--]] | |||
function p.numData(t, compress) | |||
checkType('numData', 1, t, 'table') | |||
checkType('numData', 2, compress, 'boolean', true) | |||
local ret = {} | |||
for k, v in pairs(t) do | |||
local prefix, num = mw.ustring.match(tostring(k), '^([^0-9]*)([1-9][0-9]*)$') | |||
if num then | |||
num = tonumber(num) | |||
local subtable = ret[num] or {} | |||
if prefix == '' then | |||
-- Positional parameters match the blank string; put them at the start of the subtable instead. | |||
prefix = 1 | |||
end | |||
subtable[prefix] = v | |||
ret[num] = subtable | |||
else | |||
local subtable = ret.other or {} | |||
subtable[k] = v | |||
ret.other = subtable | |||
end | |||
end | |||
if compress then | |||
local other = ret.other | |||
ret = p.compressSparseArray(ret) | |||
ret.other = other | |||
end | |||
return ret | |||
end | end | ||