lua-users home
lua-l archive

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


On Thu, Feb 25, 2010 at 01:25, Roberto Ierusalimschy
<roberto@inf.puc-rio.br> wrote:
> Of course, you can write "loadin(_ENV, string)" and then make the
> string share the lexical scope of its call site. But you must pass _ENV
> explicitly; nobody can access it outside its lexical scope (except using
> the debug API).

I'm sorry to pollute the discussion with a n00b question, but I don't
understand how changing the environment affects lexical scope...

What I understand so far:

1) Locals in Lua work like Scheme variables, they have a lexical scope
which is bound as a closure to any function defined in it.

2) Globals in 5.1 or non locals in the upcoming 5.2w behave like
dynamically scoped variables, like for example in EMACS Lisp.

>From what I understood previously, I thought that the changing the
environment only affects the second type of variable.

myenv={}
local upval
baz = function() return upval end
do
	local g, _ENV = _ENV, myenv
	g.foo = function() a=1 ; upval=2 end
end

print(upval and myenv.a or "Both are nil.")
foo()
print(upval and myenv.a and (not (_ENV.upval or myenv.upval) ) or "Bad
mental model.")


But after reading your answer, I'm puzzled:

would
local a = 1
loadin(_ENV,"a=2")

change the value of the local, or create _ENV.a? From what I
understand I'd say the latter, but I understand " "loadin(_ENV,
string)" [will] make the string share the lexical scope of its call
site " as the former...

Could you enlighten me?