lua-users home
lua-l archive

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

On Fri, 7 Sep 2001, Russell Y. Webb wrote:

> > for k, v in tab do
> >    local v = v
> >    actors[k] = function (x) act_on(v, x) end
> > end
> [...]
> Wouldn't v just be found as a local of the next block up and have the
> correct value to be bound when actors[k] is defined?  Why does it have to be
> copied to the immediately enclosing block?

I guess ET answered that (indirectly). The original 'v' is only one
variable through the whole loop, so all closures will share this same
variable, which by the end of the loop will have nil (or the last
v in the table) as its value. The "local v=v" creates a new 'v' inside the
loop, so there is a new 'v' for each loop iteration. This new variable
gets the current value of the out 'v' for that step and keeps this value
forever (nobody changes its value).

-- Roberto