lua-users home
lua-l archive

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



On Tue, Dec 16, 2008 at 10:37 AM, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:
> I've already learned something new from reading through Roberto's - in the
> middle of a pairs()/next() loop, it is no problem to change the *current*
> key in the table (previously I had believed that tables should not be
> modified at all when traversing them). Setting a different key may cause the
> loop to terminate early if you are setting the value to nil, or trigger a
> rehash if it is not. But setting the current key to something else,
> including nil, should always be fine. Is that right?

The explanation for next mentions this:

 The behavior of next is undefined if, during the traversal, you assign
 any value to a non-existent field in the table. You may however modify
 existing fields. In particular, you may clear existing fields.

 http://www.lua.org/manual/5.1/manual.html#pdf-next

Ah, so I was yet still wrong - you can clear other keys (set them to nil) without a problem, as well. next()/pairs() will just skip over nil entries, so the loop won't go wrong. Sorry for missing that bit in the manual, thank you for pointing it out.