Search code examples
lualua-table

How to remove key value from the table in loop in Lua


So, I created a table A_table and my goal is to create a set of three hands Hand and then I wanted to remove the last two sets from the table i.e key 2 and 3

A_table = {}

for i = 1, 3 do
  local  Hand = {
            ['parts'] = {
                type = 'arm',
                left = 'up',
                right = 'down',
                collision = 'true'
            }
        }
    
    table.insert(A_table, Hand)
end

for k, v in pairs(A_table) do
    print(k, v['parts'].left)
end

Output: -- Wanted to remove 2 and 3

1       up
2       up
3       up

I tried the following method but it didn't work.

for k, v in pairs(A_table) do
    for i = #v, 2, -1 do
        A_table[i] = nil
    end
end 

Solution

  • In your case...

    for i = #A_table, 2, -1 do
        table.remove(A_table)
    end
    
    1. The loop starts at last key and leaves after key number 2
    2. table.remove() without positional parameter removes last key/value by default