First of all, it loads APIs into the global environment, and that is not a good practice.
You also can't properly load APIs with a .lua extention and you can't load APIs from strings.
With this piece of code you can load APIs into local variables from files or strings.
It is compatible with almost all APIs made for ComputerCraft.
I recommend you copy and paste this into your program, because it is not supposed to be loaded as an API.
Code:
function loadAPI(path)
local env = {}
setmetatable(env, {__index = _G})
local fn, err = loadfile(path, env)
if fn then
local ok, err = pcall(fn)
if not ok then
error(err)
end
else
error(err)
end
local api = {}
for k,v in pairs(env) do
if k ~= "_ENV" then
api[k] = v
end
end
return api
end
function loadAPIString(name, str)
local env = {}
setmetatable(env, {__index = _G})
local fn, err = loadstring(str, name)
if fn then
setfenv(fn, env)
local ok, err = pcall(fn)
if not ok then
error(err)
end
else
error(err)
end
local api = {}
for k,v in pairs(env) do
if k ~= "_ENV" then
api[k] = v
end
end
return api
end
Usage:loadAPI(apipath) - Returns the API if successful, or else it errors.
loadAPIString(apiname, apistring) - Returns the API if successful, or else it errors.
If you want to load an API without having to put it in an external file,
you can use my converter which converts Lua source code into a Lua string that you can paste into your program.
Screenshot:
Download
It requires Microsoft .NET 4.0 to be installed on your computer.
Buttons:
Paste - Pastes the Lua source code from the clipboard into the input textbox.
Convert - Converts the Lua source code to a Lua string.
Copy - Copies the output Lua string into the clipboard.
I hope it helps you with making programs.
If you have any questions, bug reports or suggestions then please leave a reply.