Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a lua table entry by its key?

Tags:

key

lua

lua-table

I have a lua table that I use as a hashmap, ie with string keys :

local map = { foo = 1, bar = 2 } 

I would like to "pop" an element of this table identified by its key. There is a table.remove() method, but it only takes the index of the element to remove (ie a number) and not a generic key. I would like to be able to do table.remove(map, 'foo') and here is how I implemented it :

function table.removekey(table, key)     local element = table[key]     table[key] = nil     return element end 

Is there a better way to do that ?

like image 689
Wookai Avatar asked Nov 18 '09 20:11

Wookai


People also ask

How do you remove an entry from a Lua table?

remove () function removes a value from an array using the index position of the value to be removed. This function removes the element at the pos position from the table. This causes other elements to shift down to close the space, if necessary. This function returns the value that we remove from the table.

Are Lua tables hash tables?

We all know that a Lua table is a hash table, which uses a hash function to map a key into one of the table's slots. However, the result of the hash function is not unique. There exist some keys that have the same hash value, i.e., it may map some different keys into the same slot.

How does a table work in Lua?

Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.


1 Answers

No, setting the key's value to nil is the accepted way of removing an item in the hashmap portion of a table. What you're doing is standard. However, I'd recommend not overriding table.remove() - for the array portion of a table, the default table.remove() functionality includes renumbering the indices, which your override would not do. If you do want to add your function to the table function set, then I'd probably name it something like table.removekey() or some such.

like image 79
Amber Avatar answered Sep 21 '22 03:09

Amber