lua-users home
lua-l archive

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


The reason closures (a la Scheme, for example) all reference the same copy
of the variable in the outer scope is that it makes it easier to construct a
number of things like objects where the variables in the outer scope are
shared state. _Structure and Interpretation of Computer Programs_ probably
covers this in a lot more depth.

So, this isn't really a question of closure definition. The question is: Do
the loop variables exist at the level of the for statement or are they newly
instantiated on each pass through the loop? The latter would probably be
more expensive depending on how variable instantiation and closures are
handled.

You should be able to get what you want by writing:

    local function makeBinding(v)
        return function(x) return g(v,x) end
    end

    for k,v in pairs(t) do
       g_bindings[k] = makeBinding(v)
    end

But I am far from an expert in Lua and I haven't tested this.

Mark

on 4/28/03 5:09 PM, RLake@oxfam.org.uk at RLake@oxfam.org.uk wrote:

> I know this was brought up before (by me, amongst, I think, others) but I
> wonder if it would be possible to reopen the debate about whether automatic
> variables in for loops are new bindings or not.
> 
> It seems to me that constructions like this:
> 
> for k, v in pairs(t) do
> g_bindings[k] = function(x) return g(v, x) end
> end
> 
> ought to "work" (i.e. the functions that are inserted into g_bindings ought
> to be bound to different instances of v.)
> 
> I can think of a number of cases in which having separate bindings of the
> automatic variables makes sense, but I have not yet been able to think of a
> good example where it makes sense to have a single binding ... maybe that
> is just my own prejudice at work, so I would welcome any counter-examples.