Skip to content

Instantly share code, notes, and snippets.

@hishamhm
Created Oct 19, 2011
Embed
What would you like to do?
Attempt at a sane design for module() for Lua 5.2 - Take 5
-- Attempt at a sane design for module() for Lua 5.2 - Take 5
local lua_libs = {}
for k,v in pairs(package.loaded._G) do
lua_libs[k] = v
end
local function loader(name, modpath)
local mod, env = {}, {}
env.module = function (name)
mod._NAME = name
setmetatable(env, { __index = function(t,k)
return rawget(mod, k) or rawget(lua_libs, k)
end,
__newindex = mod })
return env
end
local fh = assert(io.open(modpath, 'rb'))
local source = fh:read'*a'
fh:close()
local ret = assert(load(source, modpath, 'bt', env))(name)
return ret or mod
end
-- replace Lua loader
package.searchers[2] = function (name)
local modpath, msg = package.searchpath(name, package.path)
if modpath then
return loader, modpath
else
return nil, msg
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment