Search code examples
lualua-table

Can't remove an item from a table


I can't remove an item from a table and I don't know why.

table: 13411d36

Code

participator = {"Zeroo#7497"}
for i, v in pairs(participator) do
    table.remove(participator, i)
end

Output

Runtime Error : org.luaj.vm2.LuaError: Zeroo#7497.lua:488: invalid key to 'next'

Why is this happening and how to fix it?


Solution

  • A table.remove() do a shifting if it not removes the last key/value pair.
    ( If key 1 is removed key 2 becomes key 1 and so on )
    Thats a problem for pairs (next).
    Better, faster and safer is to make a countdown and let table.remove() delete the last key/value pair what is the default for the remove function.
    That dont shifting the table.
    Example:

    participator = {"one", "two", "three"}
    
    for i = #participator, 1, -1 do
        print('Deleting:', i, table.remove(participator))
        print('Size:', #participator)
    end
    

    That makes...

    Deleting:   3   three
    Size:   2
    Deleting:   2   two
    Size:   1
    Deleting:   1   one
    Size:   0