Repository navigation
Expand file tree
/
Copy pathrequireAPI.lua
More file actions
57 lines (50 loc) · 1.51 KB
/
Copy pathrequireAPI.lua
File metadata and controls
57 lines (50 loc) · 1.51 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
-- loads an API file and returns it like require does
-- compatibility is NOT guaranteed
local expect = require("cc.expect").expect
local tAPIsLoading = {}
function requireAPI(_sPath)
expect(1, _sPath, "string")
local sName = fs.getName(_sPath)
if sName:sub(-4) == ".lua" then
sName = sName:sub(1, -5)
end
if tAPIsLoading[sName] == true then
printError("API " .. sName .. " is already being loaded")
return
end
tAPIsLoading[sName] = true
local shim = setmetatable({}, { __index = _G })
shim.os = setmetatable({
loadAPI = function(path)
expect(1, path, "string")
local sName = fs.getName(_sPath)
if sName:sub(-4) == ".lua" then
sName = sName:sub(1, -5)
end
shim[sName] = requireAPI(path)
return true
end,
--[[unloadAPI = function(path)
-- TODO: implement properly
end]]
}, { __index = _G.os })
local tEnv = setmetatable({}, shim) -- TODO: is this right? should it be setmetatable({}, { __index = shim })?
local fnAPI, err = loadfile(_sPath, nil, tEnv)
if fnAPI then
local ok, err = pcall(fnAPI)
if not ok then
tAPIsLoading[sName] = nil
return error("Failed to load API " .. sName .. " due to " .. err, 1)
end
else
tAPIsLoading[sName] = nil
return error("Failed to load API " .. sName .. " due to " .. err, 1)
end
local tAPI = {}
for k, v in pairs(tEnv) do
if k ~= "_ENV" then
tAPI[k] = v
end
end
return tAPI
end