local origrequire = require
local compiler = loadstring or load
local modules = {
-- for example neverlose/clipboard, you steal the src from nl website, you paste here the code and bum works
["neverlose/clipboard"] = function(require)
-- code here
end,
}
local loaded = {}
local loading = {}
local custom_require
local function make_env(modname)
return setmetatable({
require = custom_require,
_MODULE = modname
}, {
__index = _G
})
end
local function load_embedded_module(lib, def)
if loaded[lib] ~= nil then
return loaded[lib]
end
if loading[lib] then
error("circular require detected for module: " .. lib, 2)
end
loading[lib] = true
local ret
local t = type(def)
if t == "function" then
local ok, result = pcall(def, custom_require, lib)
loading[lib] = nil
if not ok then
error(("failed to load module '%s': %s"):format(lib, tostring(result)), 2)
end
ret = result
elseif t == "table" then
loading[lib] = nil
ret = def
elseif t == "string" then
if not compiler then
loading[lib] = nil
error(("module '%s' is stored as source string, but load/loadstring is unavailable"):format(lib), 2)
end
local chunk, err = compiler(def, "@" .. lib)
if not chunk then
loading[lib] = nil
error(("failed to compile module '%s': %s"):format(lib, tostring(err)), 2)
end
if setfenv then
setfenv(chunk, make_env(lib))
end
local ok, result = pcall(chunk, lib)
loading[lib] = nil
if not ok then
error(("failed to load module '%s': %s"):format(lib, tostring(result)), 2)
end
ret = result
else
loading[lib] = nil
error(("unsupported embedded module type for '%s': %s"):format(lib, t), 2)
end
if ret == nil then
ret = true
end
loaded[lib] = ret
return ret
end
custom_require = function(lib)
local def = modules[lib]
if def ~= nil then
return load_embedded_module(lib, def)
end
return error("require: " .. lib)
--return origrequire(lib)
end; require = custom_require