lua-users home
lua-l archive

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



On Tue, Aug 10, 2010 at 12:23 PM, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
Currently we see _ENV more as a simple way to define how globals work
(and the dependency between a chunk and the global table) than as a
mechanism for module construction.

Nevertheless, I should mention that there are very few details of
how _ENV works:

- all chunks (the unit of 'loading' in Lua) are compiled as if they
were a function defined under a "local _ENV" declaration. (In 5.1,
all chunks are already compiled as if they were a function; the only
novelty is this upvalue _ENV.)

- all references to undeclared variables are syntactically translated to
_ENV.varname. ("syntactically" means that the compiler rewrites 'x' as
'_ENV.x' and follows from there.)

- when a chunk is loaded with 'load' and the like (loadstring, loadfile,
dofile, etc.), its external _ENV variable gets the value of the global
table. When a chunk is loaded with 'loadin', _ENV gets the value
given as argument.

-- Roberto

So based on this I think what I'm really asking for is that something like:

foo = namespace
    local x = 99
   function bar(y) print(x+y) end
end

would be the same as:

foo={}
loadin(foo, [[
    local x = 99
    function bar(y) print(x+y) end
]])

I have no idea how others feel about it, but to me this would be tremendously useful and simple to use.  What I'm really trying to do here is to be able to limit the scope of variables for a chunk of code without having to put the code in a separate file.