The wiki has moved!

Visit the new wiki at stationeers-wiki.com The old wiki here at legacy.stationeers-wiki.com will sunset eventually.

Edits made after the 7th of March 6PM EST were NOT carried over to the new server as previously announced right here in this box.

 Actions

Module

TableTools

From Unofficial Stationeers Wiki

Revision as of 05:40, 15 December 2013 by Mr. Stradivarius (talk) (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