• Subject: Re: Iteration problems: Not a weak table issue
• From: Tiago Dionizio <tngd81@...>
• Date: Thu, 2 Dec 2004 00:55:12 -0800

```On Wed, 01 Dec 2004 16:08:42 -0800, Mark Hamburg <mhamburg@adobe.com> wrote:
> on 12/1/04 3:17 PM, Tiago Dionizio at tngd81@gmail.com wrote:
> > I can only assume that changing keys of a table (in general) isn't a
> > safe operation when iterating it using the lua_next function.
> >
> > A solution to iterate weak tables like in the example you provide this
> > should work:
> >
> > \$ lua
> > Lua 5.0.2  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
> >> function fst(t) return (function(t, key) key = next(t, key) return key,
> >> t[key] end), t, nil end
> >> t = { a = 1, b = 2, c = 3, d = 4, e = 5 }
> >> for k, v in fst(t) do t[k] = nil print(k, v) end
>
> I think you just defined pairs since I believe that
>
>     function( t, key )
>         key = next( t, key )
>         return key, t[ key ]
>     end
>
> Is equivalent to next. ("next returns the next index of the table and the
> value associated with the index.")
>
> Furthermore, in Lua 5.1 if you take your loop and insert a call to
> collectgarbage after the assignment, the loop will error out.

oops.. i originally thought of implementing that function to always
get the *first* key/value pair of the table.

function (t)
local key = next(t, nil)
return key, t[key]
end

Sorry for the confusion.

Tiago

```