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

os.loadAPI( )

Started by GreenGene, 28 October 2015 - 01:52 AM
GreenGene #1
Posted 28 October 2015 - 02:52 AM
Hello! I was am making a program, and I was wondering, does anyone know the code for os.loadAPI() or atleast how it works? Thanks!
Edited on 28 October 2015 - 01:54 AM
HPWebcamAble #2
Posted 28 October 2015 - 03:01 AM
https://github.com/alekso56/ComputercraftLua/blob/master/bios.lua#L548


That's from a Github repository. If you ever want to dig into CC's Lua files without opening the CC Jar (which you could also do), you can use this.
I've got a link in the 'Helpful Stuff' spoiler on my profile if you ever need it
Bomb Bloke #3
Posted 28 October 2015 - 03:16 AM
A basic outline of what it's doing is that it loads the API file as a function, then creates a new table to use as the environment for that function (which it metatables together with _G, the regular environment).

All global variables generated by a function go into its environment table, so when the API's code has finished execution, all the global functions it defined are contained within the custom table os.loadAPI() set as its environment. It copies those into another table using a pairs loop (which doesn't see _G from the metatable combination), and the final result is the loaded API table: which gets slotted into _G for other scripts to access.

There's also some stuff to prevent multiple scripts attempting to simultaneously load the same API at once (eg via multishell), but that's just there to deal with an edge case.