Skip to content

Instantly share code, notes, and snippets.

@MCJack123
Last active July 1, 2019 05:09
Show Gist options
  • Save MCJack123/62492cca4998c124befe3977a4de7340 to your computer and use it in GitHub Desktop.
Save MCJack123/62492cca4998c124befe3977a4de7340 to your computer and use it in GitHub Desktop.
ComputerCraft script to call a function in an API
-- Syntax: runapi <file> <func> [<format> <args...>]
-- format argument is in the format [bnstx]+
-- Example: runapi CCWinX/CCWinX.lua QueueEvent snbt CustomEvent 0 false {test=true,text="Hello\sWorld!"}
local args = {...}
if args[2] == nil then error("Usage: runapi <file> [<format> <args...>]") end
local file = table.remove(args, 1)
if not os.loadAPI(file) then error("Could not load API at " .. file) end
local apiname = string.gsub(fs.getName(file), ".lua", "")
local api = _G[apiname]
if api == nil then error("Could not determine name of API (tried " .. apiname .. ")") end
local func = table.remove(args, 1)
if type(api[func]) ~= "function" then
os.unloadAPI(apiname)
error(apiname .. "." .. func .. " is not a function")
end
if args[3] ~= nil then
local argv = {}
local format = table.remove(args, 1)
for k,v in pairs(args) do
local f = string.sub(format, k, k)
if f == "b" then argv[k] = v == "true" and true or false
elseif f == "n" then argv[k] = tonumber(v)
elseif f == "s" then argv[k] = string.gsub(string.gsub(v, "\\n", "\n"), "\\s", " ")
elseif f == "t" then argv[k] = textutils.unserialize(string.gsub(string.gsub(v, "\\n", "\n"), "\\s", " "))
elseif f == "x" then argv[k] = nil end
end
print(api[func](table.unpack(argv)))
else print(api[func]()) end
os.unloadAPI(apiname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment