lua-users home
lua-l archive

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


On Tue, Oct 23, 2012 at 2:48 PM, Elias Barrionovo
<elias.tandel@gmail.com> wrote:
> On Tue, Oct 23, 2012 at 7:19 PM, Coda Highland <chighland@gmail.com> wrote:
>> Then you would be wrong. :P You can still consider it a closure if it
>> COPIES the scope instead of REFERENCES it. The ability to modify the
>> state of a closure after it's created isn't a requirement to the
>> definition of a closure.
>
> As a matter of fact, Python does not allow one to modify the closure state:
>
> #closure.py
> def new_inc()
>    i =0
>    def inc(n):
>         i += n
>         return i
>     return inc
>
> inc1 = new_inc()
> print(inc1(2))
>
> Traceback (most recent call last):
>   File "closure.py", line 9, in <module>
>     print(inc1(1))
>   File "closure.py", line 4, in inc
>     i += n
> UnboundLocalError: local variable 'i' referenced before assignment
>
> --
> NI!
>

Not quite true:

>>> def new_inc():
...     i = [0]
...     def inc(n):
...         i[0] += n
...         return i[0]
...     return inc
...
>>> inc1 = new_inc()
>>> inc1(2)
2
>>> inc1(2)
4

The issue you encountered there with "i += n" is that it expands to "i
= i + n", which declares i as a local variable first and THEN tries to
look up its value, but it's uninitialized. In Python, ALL assignment
operations act on locals unless explicitly made global. In Lua, by
contrast, an assignment without the "local" keyword applies to the
variable declared in the nearest enclosing scope, creating a new
global if nothing is found in between.

/s/ Adam