How to remove Lua table entry by its key?


Let’s consider an example where we would like to remove a Lua table entry. The table itself behaves like a hashmap, where it has several key value pairs, and we would like to remove an entry from that table on the basis of the key.

Lua library does provide a function that we can use for our specific case. The function is table.remove() and it takes two arguments, the first argument is the name of the table and the second argument is the key that we want to remove.

Example

Consider the example shown below −

 Live Demo

local mapone = { [1] = 10, [2] = 20, [3] = 30 }
for _,v in pairs(mapone) do print(v) end
table.remove(mapone,2)
for _,v in pairs(mapone) do print(v) end

In the above example, we had a table named mapone which behaves like a hashmap, with different key-value pairs, and we wanted to remove an entry from it by providing a key, we did just that when we called the table.remove() function.

Output

10
20
30
10
30

It should be noted that the first three numbers are the values of the keys that were present in the map, and the last two numbers are values of the keys that remain in the map once we removed the key = 2.

It should also be noted that the table.remove() function only works in case we have integer keys.

In order to make it work on keys that are not integers, we would have to create our own function.

Example

Consider the example shown below −

 Live Demo

local map = { foo = 1, bar = 2 , car = 3}
function table.removekey(table, key)
   local element = table[key]
   table[key] = nil
   return element
end
for i,v in pairs(map) do print(i,v) end
table.removekey(map,'bar')
for i,v in pairs(map) do print(i,v) end

Output

foo 1
bar 2
car 3
foo 1
car 3

Updated on: 20-Jul-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements