Created
October 19, 2011 15:34
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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