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
<steve.j.donovan@gmail.com> wrote:
> On Wed, Oct 19, 2011 at 9:09 AM, Hisham <hisham.hm@gmail.com> 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
 end
 setmetatable(env, {
    __index = lua_libs, -- resolve known globals
 })
 local fh = assert(io.open(modpath, 'rb'))
 local source = fh:read'*a'
 fh:close()
 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
 end
 return mod
end

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 https://gist.github.com/1297868

steve d.