lua-users home
lua-l archive

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

On Wed, Oct 19, 2011 at 11:04 AM, steve donovan
<> wrote:
> On Wed, Oct 19, 2011 at 9:09 AM, Hisham <> wrote:
>> and your example shows how that can be a problem. Take 2, then: I
>> believe the following addresses this issue, and I couldn't spot any
>> side effects.

Take 4 should be easier to understand:

local function loader(name, modpath)
 local env = {}
 env.module = function (name)
   env._NAME = name
   return env
 setmetatable(env, {
    __index = lua_libs, -- resolve known globals
 local fh = assert(, 'rb'))
 local source = fh:read'*a'
 local ret = assert(load(source, modpath, 'bt', env))(name)
 if ret then return ret end -- explicit table was returned
 local mod = {}
 -- the module is a copy of the environment after initial loading
 for k,v in pairs(env) do
    mod[k] = v
 return mod

Very little metamagic left, except the old trick used by package.seeall.

Here it's more explicit that what we call the module is actually a
copy of the environment used when loading modules.

Full code lives at

steve d.