Module:TableTools
From Tardis Wiki, the free Doctor Who reference
Taken from Wikipedia's Module:TableTools for use with Module:Anchor.
-- This module includes a number of functions that can be useful when dealing with Lua tables.
local p = {}
-- Define often-used variables and functions.
local floor = math.floor
local infinity = math.huge
--[[
-----------------------------------------------------------------------------------
-- Helper functions
-----------------------------------------------------------------------------------
--]]
local function isPositiveInteger(num)
-- Returns true if the given number is a positive integer, and false if not.
if type(num) == 'number' and num >= 1 and floor(num) == num and num < infinity then
return true
else
return false
end
end
--[[
-----------------------------------------------------------------------------------
-- compressSparseArray
--
-- This takes an array with one or more nil values, and removes the nil values
-- while preserving the order, so that the array can be safely traversed with
-- ipairs.
-----------------------------------------------------------------------------------
--]]
function p.compressSparseArray(t)
local nums, ret = {}, {}
for k, v in pairs(t) do
if isPositiveInteger(k) then
nums[#nums + 1] = k
end
end
table.sort(nums)
for _, num in ipairs(nums) do
ret[#ret + 1] = t[num]
end
return ret
end
return p