Some functions for handling tables

Share your scripts and packages with other Mudlet users.
Post Reply
Posts: 27
Joined: Fri Jun 26, 2015 8:52 am

Some functions for handling tables

Post 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
	while i>0 do
		if keys[i] == k then
			table.remove(keys, i)
			table.remove(values, i)
		i = i - 1
	local a = {}
	for i = 1,#keys do
		a[keys[i]] = values[i]
	return a

-- 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)
        setmetatable(copy, deepcopy(getmetatable(orig)))
    else -- number, string, boolean, etc
        copy = orig
    return copy

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

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

Post Reply