Re: Lua5.0 new "For" question
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: Lua5.0 new "For" question
- From: Eero Pajarre <epajarre@...>
- Date: 2002年12月22日 23:16:52 +0200
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=789
f = function() return x end --global f
print(f());
x=123;
print(f());
end
fie() -- will print 789 newline 123
Apparently, 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