Module:TableTools

    From Nonbinary Wiki
    Revision as of 10:40, 15 December 2013 by m>Mr. Stradivarius (start module with useful tools for dealing with Lua tables)
    (diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

    Documentation for this module may be created at Module:TableTools/doc

    -- 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