lua-users home
lua-l archive

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


On Tue, Aug 10, 2010 at 1:42 PM, Shawn Fox <shawnkfox@gmail.com> wrote:
>
> 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
> ]])

No need to do any compiling (load*). Just do:

do
  local _ENV = {};
  function f (...)
    local x = 99
    function bar(y) print(x+y) end
  end
end

-- 
- Patrick Donnelly