>>> def makeAdder2(x):
v = x
def inc(y):
v += y
return v
return inc
>>> f2 = makeAdder2(3)
>>> f2(4)
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
f2(4)
File "<pyshell#13>", line 4, in inc
v += y
UnboundLocalError: local variable 'v' referenced before assignment
>>>
It looks like you can't mutate variables in a closure. Am I doing it wrong? If you really can't, that seriously limits their power.
--
In Lua:
> function adder(x)
local v = x
function inc(y)
v = v + y
return v
end
return inc
end
>> >> >> >> >> >> >> > f = adder(3)
> =f(4)
7
> =f(4)
11
> =f(4)
15
>
You may need to add a 'global' statement or something similiar. If you are going to mutate a variable in a function Python assumes that you want to create a new variable in that scope.
Generally I do not mutate variables as far as possible, so I have not hit this problem myself, yet. Perhaps there is someone more knowledgeable about Python to step in.
--
In Lua:
Works fine. (Also, the syntax is really clean.)