lua-users home
lua-l archive

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


2010/1/10 Peter Odding <peter@peterodding.com>:
> I've always considered package.seeall an ugly solution because it makes
> module tables shadow the globals table and I'm pretty sure I'm not
> the only one [1]. Therefor I've always used the following code:
>
> module(..., function(_M)
>  setfenv(3, setmetatable({}, {
>    __index = function(_, k) return _M[k] or _G[k] end,
>    __newindex = function(_, k, v) _M[k] = v end,
>  }))
> end)
>
> Can anyone tell me whether there is a way to accomplish the goal of
> separating the module environment from the module table in Lua 5.2.0
> (work1) without using the debug library? The reason I (and others)
> insist on not using the debug library is because it's labeled
> `debug' and the reference manual explains the name very clearly:

I think the new way to write modules will be:

in module(...) do
    <module content>
end

So you write instead one time:
local oldmodule = module
function module(...)
    local _M = oldmodule(...)
    return setmetatable({}, {
        __index = function(_, k) return _M[k] or _G[k] end,
        __newindex = function(_, k, v) _M[k] = v end,
    })
end

And write all your modules with the syntax using a lexical scope.

The new syntax allow to chain module modifiers (like your "private
seeall") without using 'module' extra parameters (which may be
deprecated in the future). In other words we may one day have to
replace:

module(..., package.seeall)

by:

in package.seeall(module(...)) do
end

I think it's cleaner. But that's just one use of setfenv, and as
others I think I'll miss that function.