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.

2 thoughts on “Lua table remove by key

  1. Why not simply write this function the following way?

  2. 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 *

ten × 1 =