lua-users home
lua-l archive

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


Consider the following code snippet:

t = { a = 1, b = 2, c = 3, d = 4, e = 5 }

for k, v in pairs( t ) do
    t[ k ] = nil
    collectgarbage()
    print( k, v )
end

It generates:

a    1
error: invalid key for `next'


On the other hand, the following code:

t = { a = 1, b = 2, c = 3, d = 4, e = 5 }

for k, v in pairs( t ) do
    collectgarbage()
    print( k, v )
    t[ k ] = nil
end

Produces:

a    1
c    3
b    2
e    5
d    4


I thought it was legal to assign nil to existing keys inside a loop. Are
there further caveats that need to be observed in Lua 5.1?

Mark

P.S. I would still like some assurance about how to safely iterate a weak
table.