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=”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.

3 thoughts on “Lua table remove by key

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

    1. 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.

  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 *

sixty four − 62 =