[prev in list] [next in list] [prev in thread] [next in thread] 

List:       lua-l
Subject:    Re: Closure fails to register loop variable upvalues?
From:       "Aaron Brown" <aaron-lua () oakadaptive ! com>
Date:       2005-10-28 5:16:39
Message-ID: 000601c5db7e$c7b5a660$3d0b090a () dell
[Download RAW message or body]

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

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic