-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoRequire.lua
More file actions
40 lines (36 loc) · 968 Bytes
/
autoRequire.lua
File metadata and controls
40 lines (36 loc) · 968 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
local mt = setmetatable
local rawset = rawset
local rawget = rawget
local pattern = "([^%.]+)$"
local _autoRequire = function(cls)
local impl = rawget(cls, "__IMPL")
if impl == nil then
impl = require(cls.__RPATH)
rawset(cls, "__IMPL", impl)
mt(cls, impl)
end
return impl
end
local _autoRequireRoot = {
__index = function(cls, key)
local impl = _autoRequire(cls)
return impl[key]
end,
__newindex = function(cls, key, value)
local impl = _autoRequire(cls)
impl[key] = value
end,
__call = function(cls, ...)
local impl = _autoRequire(cls)
return impl(...)
end
}
local _getModuleName = function(path, moduleName)
if not moduleName then
moduleName = string.match(path, pattern) or path
end
return moduleName
end
function autoRequire(path, moduleName)
_G[_getModuleName(path, moduleName)] = mt({__RPATH = path}, _autoRequireRoot)
end