lua-users home
lua-l archive

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


2013/9/27 Rafis Ganeyev <rafisganeyev@gmail.com>:

> Another gotcha (Lua so hard to use :( )

It becomes easier as you go along, particularly if you spend
some time reading the manual and "Programming in Lua".

> 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
>
> This will not delete element t[1].

Of course it won't. You have programmed the following:

i=1
while true do
  if t[i] does not exist, break
  remove t[i] and move down the others
  i=i+1
end

You can delete any element you like, but you must remember
that 'remove' changes the association between elements and
keys.