lua-users home
lua-l archive

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


Perhaps it would useful to explain what the compiler does. As I understand it a file or string gets translated and evaluated to the equivalent of:

  return function(...)
    <<< your file/string content here >>>
end)( <<< current environment >>> )

and any unbound variable 'x' in the file gets rewritten to _ENV["x"] (or equivalently _ENV.x)

Assigning to _ENV is just that, assigning to a variable.

And unless I'm completely barking up the wrong tree that's all the magic there is.


On Tue, 17 Aug 2010, Roberto Ierusalimschy wrote:

I think it's not pretty because what I want to say is: "redirect
global symbol lookup to this table", and not: "assign this table to
a variable". I realise, of course, that _by_ assigning this table to
_ENV, I get the lookup redirection, but that's implicit. This one
symbol in the language is overloaded. It's magic.


See that's part of my issue with _ENV = { ... }. It's a reuse of
existing syntax, but as a special case. However, nothing is perfect
and the consensus seems to be that we can live with this one bit of
magic in an otherwise perfect language ;)

I am not sure you have a correct understanding of how _ENV works. Any
reference to a "global" name 'x' ("global" here meaning a name
without any local declaration) is always translated to _ENV. That
is, if you write "x = x + 1", Lua reads this as "_ENV.x = _ENV.x +
1". That is all. Apart from this translation, _ENV is a completely
normal variable. An assignment to _ENV is a completely normal
assignment. There is nothing magic or special at all happening there.
_ENV is represented, stored, and manipulated by Lua just like any other
variable. Nowhere in Lua there is code like "if this variable is _ENV
then bla-bla-bla" (except for error messages).

-- Roberto