Corona SDK Lua

Lua table remove by key

Lua has a table.remove() function that deletes an element from a table at the specified position, or the last element by default. However, it doesn’t work when the table is an associative array (e.g. {name=”swfoo”, domain=””} ).

Below is a simple function that deletes a key-value pair from a table. One important feature to note is that instead of modifying the original table, it returns a new table.

-- Remove key k (and its value) from table t. Return a new (modified) table.
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

local t = {name="swfoo", domain=""}
t = table.removeKey(t, "domain")

3 replies on “Lua table remove by key”

Why not simply write this function the following way?

function table.removeKey(t, k_to_remove)
  local new = {}
  for k, v in pairs(t) do
    new[k] = v
  new[k_to_remove] = nil
  return new

Curous6, that is how you delete the hashtag portion of a key in a table. The other portion takes up a small amount of memory. If your function is used rapidly, it can eventually cause a memory leak.

Unfortunately, the only way to prevent that is to duplicate the elements of a table into another table and have it avoid inserting the key you want to delete, then replace the previous table with the new one.

BTW, the reason table.remove() “doesn’t work when the table is an associative array ” is because it’s not needed in this case: one simply do t[whatever] = null. Actually, table.remove() isn’t strictly needed even for sequences (you can just do t[3] = nil) but it is needed if you want to keep your table a proper sequence: it moves the remaining elements down.

Leave a Reply

Your email address will not be published. Required fields are marked *