|
Hmmm... so, If I understand correctly, the closure is "frozen" or "closed" once the local x is out of scope.I find this one also interesting:function fie() local x=789f = function() return x end --global fprint(f()); x=123; print(f());end fie() -- will print 789 newline 123Apparently, you can still change the contents of the closure's x whilst the local x is in scope, because they are the same x. Which makes sense due to the lexical scoping.
You can change it even later ;-) Try: function fie() local x=123; function f() return x end function g(y) x=y end end fie(); print(f()); --prints 123 g(321); print(f()); --prints 321 This is powerfull stuff.... (Were upvalues read-only?) Btw. I became curious about what Peter had suggested year ago. I think that what he wanted (protected datatypes in Lua) might be implementable with closures. Create an object which has its internals in a closure, which can only be accessed by the interface functions, hmmm, I don't know if there are any holes here. Eero