lua-users home
lua-l archive

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


On Sat, Jan 9, 2010 at 4:07 PM, Bertrand Mansion <lua@mamasam.net> wrote:
> just a clear sign that these functions are lower-level and that there
> are now more user-friendly ways to achieve similar things.

But not _all things_. I'm thinking of Leo's use-case, where he has one
function which he wants to evaluate efficiently for a lot of different
contexts.

Here's David M's idea of private module environments done without setfenv:

-- closed_module.lua

local setmetatable,rawset,_G = setmetatable,rawset,_G

return function(name)

    local mod = module(name)

    local env,meta = {_M=mod._M,_NAME=mod._NAME,_PACKAGE=mod._PACKAGE},{}

    env._SELF = env

    meta.__index = _G

    function meta.__newindex(t,key,val)

        rawset(mod,key,val)

        rawset(env,key,val)

    end

    setmetatable(env,meta)

    return env

end



And the modules look like this:

in require 'closed_module' (...) do



function first (x)

    second(x)

end



function second (x)

    print(x)

end



end



The idea is still doable, i.e. that you can put any arbitrary junk in
the environment of the module without bothering the global table.

steve d.