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=”swfoo.com”} ).
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
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
local t = {name="swfoo", domain="swfoo.com"}
t = table.removeKey(t, "domain")
3 replies on “Lua table remove by key”
Why not simply write this function the following way?
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 dot[3] = nil
) but it is needed if you want to keep your table a proper sequence: it moves the remaining elements down.