Advertisement
Commandcracker

os.loadAPI

Oct 23rd, 2022 (edited)
1,170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.70 KB | None | 0 0
  1. -- https://github.com/cc-tweaked/CC-Tweaked/blob/f4e542b4db686dad6f3fe1c4fe0006fc06dd2bd9/src/main/resources/data/computercraft/lua/bios.lua#L6-L15
  2. local expect
  3.  
  4. do
  5.     local h = fs.open("rom/modules/main/cc/expect.lua", "r")
  6.     local f, err = loadstring(h.readAll(), "@expect.lua")
  7.     h.close()
  8.  
  9.     if not f then error(err) end
  10.     expect = f().expect
  11. end
  12.  
  13. -- https://github.com/cc-tweaked/CC-Tweaked/blob/f4e542b4db686dad6f3fe1c4fe0006fc06dd2bd9/src/main/resources/data/computercraft/lua/bios.lua#L520-L564
  14. local tAPIsLoading = {}
  15. function os.loadAPI(_sPath)
  16.     expect(1, _sPath, "string")
  17.     local sName = fs.getName(_sPath)
  18.     if sName:sub(-4) == ".lua" then
  19.         sName = sName:sub(1, -5)
  20.     end
  21.     if tAPIsLoading[sName] == true then
  22.         printError("API " .. sName .. " is already being loaded")
  23.         return false
  24.     end
  25.     tAPIsLoading[sName] = true
  26.  
  27.     local tEnv = {}
  28.     setmetatable(tEnv, { __index = _G })
  29.     local fnAPI, err = loadfile(_sPath, nil, tEnv)
  30.     if fnAPI then
  31.         local ok, err = pcall(fnAPI)
  32.         if not ok then
  33.             tAPIsLoading[sName] = nil
  34.             return error("Failed to load API " .. sName .. " due to " .. err, 1)
  35.         end
  36.     else
  37.         tAPIsLoading[sName] = nil
  38.         return error("Failed to load API " .. sName .. " due to " .. err, 1)
  39.     end
  40.  
  41.     local tAPI = {}
  42.     for k, v in pairs(tEnv) do
  43.         if k ~= "_ENV" then
  44.             tAPI[k] =  v
  45.         end
  46.     end
  47.  
  48.     _G[sName] = tAPI
  49.     tAPIsLoading[sName] = nil
  50.     return true
  51. end
  52.  
  53. function os.unloadAPI(_sName)
  54.     expect(1, _sName, "string")
  55.     if _sName ~= "_G" and type(_G[_sName]) == "table" then
  56.         _G[_sName] = nil
  57.     end
  58. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement