lua-users home
lua-l archive

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

on 11/12/04 5:19 AM, Dr. Rich Artym at wrote:

> On Fri, Nov 12, 2004 at 12:22:54AM -0800, Mark Hamburg wrote:
>> To your quotes I will throw back Sussman's _Structure And Interpretation of
>> Computer Programs_ which shows all sorts of things that you can build
>> because closures capture variables rather than values. (It covers a lot of
>> other things but review Chapter 3, Modularity, Objects, and State.
>> The closure part has to do with the fact that unlike dynamic scoping,
>> evaluating the function won't go looking for the variable again. The
>> implementation determines which variable a token corresponds to at the time
>> the function is constructed based on the lexical scope of the token. A
>> function captures it's environment at the time it is created and that
>> environment is based on the lexical arrangement of code rather than the
>> dynamic arrangement. That environment provides a mapping from variables
>> names to values.
> Thanks Mark, that's another good quote to make exactly the same point I
> was making:  "A function captures it's environment at the time it is
> created" ... and "That environment provides a mapping from variables
> names to values", ie. very specifically not a mapping from names to
> addresses of variable cells.
> What Sussman is saying so very explicitly is very very key:  the (name,value)
> pairs for each free variable in the open functional expression are "captured"
> when the closure is made (it's not an arbitrary choice of words), because it's
> precisely that capture that allows us to consider the resulting composite
> functional object (function + state) as a closed function, one without any
> to-be-evaluated dependencies apart from its lambda-bound function arguments.

It's the pairs that are captured as in they continue to refer to the same
pairs. If that pair is visible elsewhere, however, then changes to that pair
within the function will be visible outside the function and vice-versa. No
new environment is constructed when the function is created. Instead it
retains a reference to the environment in which it was created.

This is in constrast to dynamic scoping which uses the environment in effect
when the function is called.

Lua closures work just like Scheme closures. I strongly urge you to read
chapter 3 of SICP.