Skip to content

Instantly share code, notes, and snippets.

@stevedonovan
Created October 19, 2011 09:52
Show Gist options
  • Select an option

  • Save stevedonovan/1297868 to your computer and use it in GitHub Desktop.

Select an option

Save stevedonovan/1297868 to your computer and use it in GitHub Desktop.
A Custom Lua module loader for Lua 5.2
-- This allows a more restricted module() style; the key feature
-- is that each module is loaded in a custom environment, and the actual module
-- table is a copy of that environment after initial load.
-- clone _G so that globals from the program don't invade the module
local lua_libs = {}
for k,v in pairs(package.loaded._G) do
lua_libs[k] = v
end
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
-- 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
@nbghydyd983-gif
Copy link

<script src="https://gist.github.com/stevedonovan/1297868.js"></script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment