Jump to content




Advantages to APIs over global tables


3 replies to this topic

#1 KnightMiner

  • Members
  • 61 posts
  • Locationattempt to index "location" (a nil value)

Posted 19 September 2015 - 11:30 PM

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 by KnightMiner, 19 September 2015 - 11:30 PM.


#2 Lupus590

  • Members
  • 2,029 posts
  • LocationUK

Posted 19 September 2015 - 11:56 PM

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 by Lupus590, 19 September 2015 - 11:57 PM.


#3 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 20 September 2015 - 12:14 AM

 Lupus590, on 19 September 2015 - 11:56 PM, said:

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 by Bomb Bloke, 20 September 2015 - 12:17 AM.


#4 KnightMiner

  • Members
  • 61 posts
  • Locationattempt to index "location" (a nil value)

Posted 21 September 2015 - 03: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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users