Skip to content

Instantly share code, notes, and snippets.

@hishamhm
Created October 19, 2011 15:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hishamhm/1298652 to your computer and use it in GitHub Desktop.
Save hishamhm/1298652 to your computer and use it in GitHub Desktop.
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