I've been playing around with Lua. And recently in a JS issue I had I was shown how to fix it with Closures. I understood why, but. I don't understand the why behind the why. That probably makes no sense so, here's the Lua example of what I'm trying to do.
(It should be obvious what this does, whether you know Lua or not.)
Code:
function ClosureFactory ()
UpperValue = 0
return function ()
UpperValue = UpperValue + 1
return UpperValue
end
end
ClosureFactory()
ClosureFactory()
The two function calls output:
> 1
> 2
I understand how closures can access their outer context where they were created. And I understand that they maintain the value throughout continuous function calls. But what I don't understand. Is
why they maintain the value. Surely once the ClosureFactory() is called, it resets the UpperValue to 0. So the newly created closure is accessing 0 again. I've looked everywhere, at Closures in general, wikipedia, functors in C, closures in JS in Lua and Python equivalents. No where explains the theory or
why the value is maintained.
The best answer I came up with is that once the closure is returned, the closure is what is called from then on, never the factory. But that clashes with the idea that the factory produces a new closure each call.