Created
July 22, 2010 17:27
-
-
Save daurnimator/486289 to your computer and use it in GitHub Desktop.
A replacement/wrapper for lua's require
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
local _G = _G | |
local next , pairs , rawset , require = next , pairs , rawset , require | |
local cache = { } | |
---A new require: loads modules in a way that they don't modify the global environment | |
--@param lib module name to load (given to require) | |
--@param keepchanges whether changes to existing global keys should be kept (default is to revert changes) | |
local function newrequire ( lib , keepchanges ) | |
-- Check if its in the cache | |
local cachedver = cache [ lib ] | |
if cachedver ~= nil then return cachedver end | |
-- Save current _G | |
local old_G = { } | |
for k , v in pairs ( _G ) do | |
old_G [ k ] = v | |
end | |
-- Require the lib | |
local res = require ( lib ) | |
-- Save changes to _G | |
local new = { } | |
for k , v in pairs ( _G ) do | |
if old_G [ k ] == nil then | |
new [ k ] = v | |
rawset ( _G , k , nil ) -- Delete all new values | |
end | |
end | |
if not keepchanges then -- Restore old _G | |
for k , v in pairs ( old_G ) do | |
rawset ( _G , k , v ) | |
end | |
end | |
local k , v = next ( new ) | |
if not res and k ~= nil then -- Library doesn't return anything, and is not well behaved (it adds things to global env) | |
if k == lib and next ( new , k ) == nil then -- Module only loaded one value, and it was called the same thing as the lib. | |
res = v | |
else -- Return a table of everything it added to global env. | |
res = new | |
end | |
end | |
cache [ lib ] = res | |
return res | |
end | |
--This file returns the new require function and the cache. | |
return newrequire , cache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment