This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
johnnic's profile picture

Loading API help

Started by johnnic, 25 June 2014 - 01:41 AM
johnnic #1
Posted 25 June 2014 - 03:41 AM
Hey guys. I was wondering how to correctly load API's with a file extension. I have tried

os.loadAPI("API.lua");
API.lua.function();
which does not work, and neither does

os.loadAPI("API.lua");
API.function();
Do I need to rename the file, or can I use that way?
Thanks in advance
Bomb Bloke #2
Posted 25 June 2014 - 03:45 AM
You might be able to do this:

_G["API.lua"].function()

… but quite frankly, I can only recommend removing the extension.
theoriginalbit #3
Posted 25 June 2014 - 02:02 PM
Bomb Bloke is indeed correct. you would be able to access it directly through the global table and the simplest solution would be to remove the extension from the file.

however if you don't want to remove the extension or you can't remove the extension (i.e. if your text editor requires it), I did write an alternative to os.loadAPI a while back that would remove any extension if present.


local function loadAPI(path)
  --# check the file exists
  if not fs.exists(path) then
	error("File does not exist", 2)
  end
  --# check the path isn't a directory
  if fs.isDir(path) then
	error("Cannot load directory", 2)
  end
  --# get the filename and extension (if exists)
  local name = fs.getName(path)
  --# remove the extension (if exists)
  name = name:match("(%a+)%.?.-")
  --# check there isn't an API loaded under this name
  if _G[name] then
	error("API "..name.." already loaded", 2)
  end
  --# os.loadAPI logic
  local env = setmetatable({}, { __index = _G })
  local func, err = loadfile(path)
  if not func then
	error(err, 0)
  end
  setfenv(func, env)
  func()
  local api = {}
  for k,v in pairs(env) do
	api[k] =  v
  end
  _G[name] = api
  return true
end
Edited by
Bomb Bloke #4
Posted 26 June 2014 - 03:33 AM
It strikes me that you could also do this:

os.loadAPI("API.lua")
local API = _G["API.lua"]

API.function()

Still a bit messy, but certainly simple.