lua-users home
lua-l archive

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


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
same function.

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
this.)

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.

--
Aaron