lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 27.09.2013 09:38, Rafis Ganeyev wrote:
> Another gotcha (Lua so hard to use :( )

Its not, you just need to get used to it. Everyone had to.

> If you are deleting elements from collection using *pairs()*, you can't
> delete element with *table.remove()*, you must delete only element that
> *pairs()* pointed to you:
> 
> local t = setmetatable({ 1, 2 }, mt)
> for i, obj in pairs(t) do
>   obj:teardown()
>   table.remove(t)
> end
> print(#t) -- prints 1

That is because you cannot remove elements from the table while
iterating it with pairs() loop, because the order is then undefined.

The correct way would be to store keys to remove in a separate table,
then remove them outside of the loop.
If your table is a list, and you iterate with ipairs, you could remove
elements in the same loop like this:

local t = setmetatable({ 1, 2, 3, 4 }, mt)
for i=#t, 1, -1 do
  local obj=t[i]
  obj:teardown()
  table.remove(t, i)
end


Regards,
miko