Module:table

Definition from Wiktionary, the free dictionary
Jump to: navigation, search

This module contains various functions that deal with Lua tables. The remove_holes function is used by Module:parameters.


local export = {}

--[[
Takes table and returns new table
containing only the numerically indexed items,
with gaps removed.
]]
function export.remove_holes(list)
	local new_list = {}
	
	if type(list) ~= "table" then
		error('The function "remove_holes" requires a table as its first argument, but was supplied "' .. type(list) .. '".')
	end
	
	local maxindex = 0
	if not list.maxindex then
		for key, value in pairs(list) do
			if type(key) == "number" then
				if key > maxindex then
					maxindex = key
				end
			end
		end
	end

	for i = 1, list.maxindex or maxindex do
		table.insert(new_list, list[i])
	end
	
	return new_list
end

--[[
Takes table and a value to be found.
If the value is in the array portion of the table, return true.
If the value is in the hashmap or not in the table, return false.
]]
function export.contains(list, x)
	for _, v in ipairs(list) do
		if v == x then return true end
	end
	return false
end

return export