local tAPIsLoading = {}
function os.loadAPI( _sPath )
local sName = fs.getName( _sPath )
if tAPIsLoading[sName] == true then
printError( "API "..sName.." is already being loaded" )
return false
end
tAPIsLoading[sName] = true
local tEnv = {}
setmetatable( tEnv, { __index = _G } )
local fnAPI, err = loadfile( _sPath )
if fnAPI then
setfenv( fnAPI, tEnv )
fnAPI()
else
printError( err )
tAPIsLoading[sName] = nil
return false
end
local tAPI = {}
for k,v in pairs( tEnv ) do
tAPI[k] = v
end
_G[sName] = tAPI
tAPIsLoading[sName] = nil
return true
end
as seen a tEnv is created, and the function that will create the functions of the API is placed into it, then run, now all the functions have been created in tEnv, now all the functions are copied over to another table, tAPI, then that is set to the _G key (which is the api name).
A bit of a weird thing to copy them over into another table, why was that done? The result is that any "global" variable create by the functions in the API will neither be in _G nor in the api table but in the fenv of the function
so if a function in the loaded API was
function foo()
bar = "foo"
end
bar would neither be _G.bar nor in the _G,apitable.bar but getfenv(_G.apitable.foo).bar
(and why does this forum make my topic title weirdly capitalized..)