Changes
add getNumKeys function and improve the comments, add the beginnings of a sparseIpairs function
--[[
-----------------------------------------------------------------------------------
-- Helper functionsisPositiveInteger---- This function returns true if the given number is a positive integer, and false-- if not. Although it doesn't operate on tables, it is included here as it is-- useful for determining whether a given table key is in the array part or the-- hash part of the table.
-----------------------------------------------------------------------------------
--]]
if type(num) == 'number' and num >= 1 and floor(num) == num and num < infinity then
return true
return false
end
end
--[[
-----------------------------------------------------------------------------------
-- getNumKeys
--
-- This takes a table and returns an array containing the numbers of any numerical
-- keys that have non-nil values, sorted in numerical order.
-----------------------------------------------------------------------------------
--]]
function p.getNumKeys(t)
local isPositiveInteger = p.isPositiveInteger
local nums = {}
for k, v in pairs(t) do
if isPositiveInteger(k) then
nums[#nums + 1] = k
end
end
table.sort(nums)
return nums
end
--]]
function p.compressSparseArray(t)
local nums, ret = {}, {} for k, v in pairslocal nums = p.getNumKeys(t) do if isPositiveInteger(k) then nums[#nums + 1] = k end end
table.sort(nums)
for _, num in ipairs(nums) do
return ret
end
--[[
-----------------------------------------------------------------------------------
-- sparseIpairs
--
-- This is an iterator for sparse arrays. It can be used like ipairs, but can
-- handle nil values.
-----------------------------------------------------------------------------------
--]]
-- function p.sparseIpairs(t)
-- local nums = p.getNumKeys(t)
return p