Module:TableTools: Difference between revisions

From the Croc Wiki, the Croc encyclopedia
Jump to navigationJump to search
add getNumKeys function and improve the comments, add the beginnings of a sparseIpairs function
(start module with useful tools for dealing with Lua tables)
 
(add getNumKeys function and improve the comments, add the beginnings of a sparseIpairs function)
Line 9:
--[[
-----------------------------------------------------------------------------------
local function-- isPositiveInteger(num)
-- Helper functions
--
-- ReturnsThis function returns true if the given number is a positive integer, and false if not.
-- 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.
-----------------------------------------------------------------------------------
--]]
function p.isPositiveInteger(num)
 
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
Line 24 ⟶ 27:
--[[
-----------------------------------------------------------------------------------
-- getNumKeys
-- compressSparseArray
--
-- This takes ana arraytable withand onereturns oran morearray nilcontaining values,the andnumbers removes theof nilany valuesnumerical
-- keys that have non-nil values, sorted in numerical order.
-- while preserving the order, so that the array can be safely traversed with
-- ipairs.
-----------------------------------------------------------------------------------
--]]
function p.compressSparseArraygetNumKeys(t)
local nums, retisPositiveInteger = {}, {}p.isPositiveInteger
local nums = {}
for k, v in pairs(t) do
if isPositiveInteger(k) then
Line 38 ⟶ 41:
end
end
table.sort(nums)
return nums
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 ret = {}
local nums = p.getNumKeys(t)
table.sort(nums)
for _, num in ipairs(nums) do
Line 44 ⟶ 63:
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
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

Navigation menu