lua-users home
lua-l archive

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


On 3/08/2010, at 5:43 PM, David Manura wrote:

> But here's another, IMO practical, idea along the lines of supporting
> "two simultaneous environment tables":
> 
>  _ENVW,  = {}
>  _ENV = _G  -- this line actually can be omitted but is included for clarity
>  function foo() bar() end
>  function bar() print'!' end
>  return _ENVW   -- Note: rename _ENVW to something friendlier like
> _PUBLIC if you want
> 
> What this would mean is that any global variable ever written to
> within the current lexical scope (i.e. foo and bar) would be resolved
> to the _ENVW table for both reads and writes, and all other global
> variables that are only read from would be resolved to _ENV.  So, the
> above becomes bytecode-equivalent to
> 
>  local _ENVW = {}
>  local _ENV = _G  -- this line actually can be omitted but is
> included for clarity
>  function _ENVW.foo() _ENVW.bar() end
>  function _ENVW.bar() _ENV.print'!' end
>  return _ENVW
> 
> and also has basically the same bytecode as my current preferred method:
> 
>  local M = {}; function M.foo() M.bar() end; function M.bar()
> print'!' end; return M

Bytecode equivalence aside, couldn't you achieve this with:

local _ENV = setmetatable({}, { __index = _G})  -- or is that __index=_ENV now?
function foo() bar() end
function bar() print'!' end
return setmetatable(_ENV, nil)

Cheers,
Geoff