Open main menu

Wiktionary β

Module:table/sandbox

< Module:table
Text-x-generic with pencil.svg This module needs documentation.
Please document this module by describing its purpose and usage on the documentation page.

local export = {}

function export.isPositiveInteger(v)
	if type(v) == 'number' and v >= 1 and floor(v) == v and v < infinity then
		return true
	else
		return false
	end
end

-- Augments the basic equals operator with a procedure for comparing
-- tables as arrays.
function export.arrayEquals(array1, array2)
	if type(array1) ~= "table" or type(array2) ~= "table" then
		return array1 == array2
	elseif #array1 ~= #array2 then
		return false
	end
	
	for i = 1, #array1 do
		if array1[i] ~= array2[i] then
			return false
		end
	end
	
	return true
end

function export.equals(t1, t2)
	if type(t1) ~= "table" or type(t2) ~= "table" then
		return array1 == array2
	elseif #t1 ~= #t2 then
		return false
	end
	
	for k, v in pairs(t1) do
		if t2[k] ~= v then
			return false
		end
	end
	
	-- Some redundancy here: if a key is present in both tables, it will be
	-- checked twice.
	for k, v in pairs(t2) do
		if t1[k] ~= v then
			return false
		end
	end
	
	return true
end

function export.findGap(t)
	local i = 0
	for _ in pairs(t) do
		i = i + 1
		if t[i] == nil then
			return i
		end
	end
end

function export.maxIndex(t)
	local maxindex = 0
	for k in pairs(t) do
		if export.isPositiveInteger(k) and k > maxindex then
			maxindex = k
		end
	end
	return maxindex
end

local function deepcopy(orig, noMetatable, already_seen)
	-- Stores copies of tables indexed by the original table.
	already_seen = already_seen or {}
	
	local copy = already_seen[orig]
	if copy ~= nil then
		return copy
	end
	
	if type(orig) == 'table' then
		copy = {}
		for orig_key, orig_value in pairs(orig) do
			copy[deepcopy(orig_key, noMetatable, already_seen)] = deepcopy(orig_value, noMetatable, already_seen)
		end
		already_seen[orig] = copy
		
		if not noMetatable then
			local mt = getmetatable(orig)
			if mt ~= nil then
				local mt_copy = deepcopy(mt, noMetatable, already_seen)
				setmetatable(copy, mt_copy)
				already_seen[mt] = mt_copy
			end
		end
	else -- number, string, boolean, etc
		copy = orig
	end
	return copy
end

export.deepcopy = deepcopy

return export