Page 1 of 1

Some functions for handling tables

Posted: Mon Aug 03, 2015 10:25 pm
by EulersIdentity
While manipulating tables I found myself wanting to do some things for which I couldn't find an appropriate Lua function. Here are the functions I used to get these behaviors and make working with tables a little easier:
  • table.removeKey - removes an entry from a table
  • deepcopy - make an exact copy of a table
  • isMember - check if a value is in an array
  • isArray - check if a table is an indexed array
Code: [show] | [select all] lua
-- removes an entry from a table by specifying its key (table, key)
function table.removeKey(t, k)
	local i = 0
	local keys, values = {},{}
	for k,v in pairs(t) do
		i = i + 1
		keys[i] = k
		values[i] = v
	end
 
	while i>0 do
		if keys[i] == k then
			table.remove(keys, i)
			table.remove(values, i)
			break
		end
		i = i - 1
	end
 
	local a = {}
	for i = 1,#keys do
		a[keys[i]] = values[i]
	end
 
	return a
end


-- copies a table exactly
-- can potentially present problems with tables that have very
-- deep amount of levels, be sure to check the copy if you do this
-- usage: myNewTable = deepcopy(myOldTable)

function deepcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in next, orig, nil do
            copy[deepcopy(orig_key)] = deepcopy(orig_value)
        end
        setmetatable(copy, deepcopy(getmetatable(orig)))
    else -- number, string, boolean, etc
        copy = orig
    end
    return copy
end


-- check if an item is a member of a table
-- use caution if table is anything but a simple
-- dictionary or indexed array
-- returns index if it is found or first key that is found
-- returns false otherwise
-- usage: isMember(alphabet,"d") -> 4, isMember(beatles,"obama") -> false
function isMember (t,val)
	for k,v in pairs(t) do
		if v == val then
			return k
		end
	end
	return false
end

-- function to check if a table is an indiced array
-- will not return true if indices are non-sequential
function isArray(t)
  local i = 0
  for _ in pairs(t) do
    i = i + 1
    if t[i] == nil then return false end
  end
  return true
end