views:

955

answers:

1

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.remove(table, key)
    local element = table[key]
    table[key] = nil
    return element
end

Is there a better way to do that ?

+5  A: 

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.

Amber
Thanks for the feedback about the deletion. About the name of the function, this was mainly for making my point clear. I usually don't override standard functions. I will definitely not use it under that name (`table.removekey()` would my best choice, too).
Wookai
If you're only using it within a single block, you be even better off performance-wise by simply making it a local function instead (saves the overhead of a global lookup for each call). I quite often import `table.insert` and `table.remove` into the local namespace if I'm using them frequently, often as something like `tinsert()` and `tremove()`.
Amber
Thanks for the performance tip. I'll try to import the functions I use often into the local namespace to see if this makes a big difference.
Wookai