[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: modules, require, magic
- From: steve donovan <steve.j.donovan@...>
- Date: Wed, 19 Oct 2011 11:53:13 +0200
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.
- References:
- modules, require, magic, Eduardo Ochs
- Re: modules, require, magic, Javier Guerra Giraldez
- Re: modules, require, magic, Petite Abeille
- Re: modules, require, magic, Sam Roberts
- Re: modules, require, magic, David Manura
- Re: modules, require, magic, Hisham
- Re: modules, require, magic, Geoff Leyland
- Re: modules, require, magic, Hisham
- Re: modules, require, magic, steve donovan