Documentation for custom APIs
ejm554 opened this issue ยท 8 comments
I've started experimenting with custom APIs, and I'm unsure of the best way to organize and reference them. Where is the latest or best documentation for this? (That's assuming something currently exists.)
I read on wiki.computercraft.cc that os.loadAPI
is deprecated, and that require
is the preferred function. However, I'm not finding any documentation for that second function which isn't several years old.
I'm also noticing behavior that I don't expect, e.g., I can't figure out how to use prefixes before my function names, like how myAPI precedes hello in myAPI.hello()
. Or perhaps this is no longer possible? In which case, I'm confused about how to avoid namespace conflicts.
BTW, I'm using CC:T 1.85.0 with MC 1.12.2.
It sounds like we need to write a wiki page about writing APIs with require().
The general gist of require is that your API function returns a table (e.g. return myAPI
) at the end of the file, and then in other files you can import it with local myAPI = require("myAPI")
.
Here's an example API:
myAPI.lua
local myAPI = {} -- create our API table
function myAPI.hello() -- create functions as you like
return "Hello, world!"
end
-- return (or export) our API for require:
return myAPI
Using the API:
test.lua
-- import our API:
local myAPI = require("myAPI")
print(myAPI.hello()) -- Hello, world!
Edit: the best documentation about require is the lua manual. Require is not specific to CC, whereas os.loadAPI
is (and is also deprecated).
As @Lemmmy says, require
is built-in to Lua, and so I didn't really think to document it. There's a pretty nice explanation on the Lua users wiki, which goes into a bit more detail about the package
library too.
It'd be good to get a wiki article explaining the difference between os.loadAPI
and require
, and describing how to update programs/libraries to use require
. Probably worth also adding a page on require
, there's a lot of misconceptions about it.
I've written some documentation require
for the wiki. It hopefully covers most questions and issues people have with require, though I'd definitely appreciate some feedback from others. It would also be worth writing a separate page about converting APIs to use require
, if someone wants to pick that up.
There is more below that wall of links? I never realized, I thought the wiki was nearly empty :O.
I had move the links at the end of the page now. If you find another problem, you can help the wiki and fix it self. A wiki lives from user who create and edit pages.