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

Advantages to APIs over global tables

Started by KnightMiner, 19 September 2015 - 10:30 PM
KnightMiner #1
Posted 20 September 2015 - 12:30 AM
What exactly are the advantages to using an API over a global table? The reason I'm wondering is because I recently added two functions to my program Extensions, and it seems like way too few things in the table to be worth making an API over, but I still get the feeling there is some reason I should be using an API.
Edited on 19 September 2015 - 10:30 PM
Lupus590 #2
Posted 20 September 2015 - 12:56 AM
From my knowledge, there is no difference between an API (as loaded by the craftOS method) and a global table. An API would just be cleaner as it follows the standard which has been set, namely creating a table from a lua file. The shell 'API' breaks this rule as it creates the shell table without using the loadAPI function.

Once loaded an API is a global table.
Edited on 19 September 2015 - 10:57 PM
Bomb Bloke #3
Posted 20 September 2015 - 01:14 AM
Once loaded an API is a global table.

APIs loaded via os.loadAPI() are placed into _G. Simply defining a table into the global environment won't put it there.

A benefit of loading into the global environment is that you can potentially load multiple unique copies of your "API" into memory at once (one for each global environment available on the system), which is why the shell/multishell "APIs" are loaded that way (they need to be able to track the unique aspects of each running shell).

A con is that other APIs can't refer to elements in the global environment (only _G), which is why people keep making threads wondering why their attempts to use the shell API within their own APIs result in "attempt to index nil" errors.

Of course, there's nothing stopping you from dumping a table of functions directly into _G. It's just generally tidier and easier to let os.loadAPI() handle that for you. Your API functions don't need to index into your own API table in order to refer to each other, for example. It's not a big deal, though.
Edited on 19 September 2015 - 11:17 PM
KnightMiner #4
Posted 21 September 2015 - 04:21 AM
Well, I doubt I will ever need multiple copies, since all the functions really do are check data against a preloaded table. The functions being used in other APIs seems like a worthwhile advantage (and easier than dumping the table myself), so I guess I will just tweak the script a bit to be able to be loaded as an API for the sake of those functions.