[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Closure fails to register loop variable upvalues?
- From: "Aaron Brown" <aaron-lua@...>
- Date: Fri, 28 Oct 2005 01:16:39 -0400
Paul Chiusano wrote:
2: for name, fn in pairs(Obj) do
It's as if the loop variable 'fn' is not registered as an
upvalue in the closure created.
More accurately, all of the closures have the same upvalue,
rather than a new 'fn' getting created for each iteration.
This upvalue is nil because the pairs() iterator has hit the
end of the table, but if you were to break out of the loop
at the appropriate time, all of the closures would call the
As Rici mentioned, the behavior you expected is implemented
in Lua 5.1. Until then, just make a narrower scope as in
your second example. (I just reuse the same name when I do
When I first ran into this behavior, I thought that,
although it wasn't what I expected, it made at least as much
sense as what I was expecting. Since then, I've run into
this type of situation every month or two, and every single
time I've wanted a separate variable for each iteration, so
I'm glad that this is how loop variables work in 5.1.