Posted 25 November 2014 - 02:02 PM
Hello everyone (first forum post, yay ^^),
I've got a problem in understanding how the different code sources get integrated into the global environment.
My problem is in the following scenario:
After that in a lua prompt:
Running "imTest" with shell.run works fine,
but running it with os.loadAPI, which runs the whole file too, results in an error:
I can't figure out what is the reason for this, as a peek on the part of "bios.lua" where "os.loadAPI" is defined
seems to indicate that the API being loaded should have access to _G through the metatable. And as far as i can see _G should already contain "printTable" at the time of os.loadAPI("imTest") getting called.
Any insights are greatly appreciated!
Thanks,
hanno
I've got a problem in understanding how the different code sources get integrated into the global environment.
My problem is in the following scenario:
-- file: "base"
function printTable(tab, depth, indent, indentAdd)
[...]
end
-- file: "startup"
shell.run("base")
(I like to export some functions directly in the global namespace, especially the ones i use often from the lua shell. So i run them with shell.run from the startup file.)
-- file: "imTest"
print("imTest started.")
printTable({hans="wurst", foo="bar"})
After that in a lua prompt:
Running "imTest" with shell.run works fine,
lua> shell.run("imTest")
imTest started.
hans = wurst
foo = bar
true
but running it with os.loadAPI, which runs the whole file too, results in an error:
lua> os.loadAPI("imTest")
imTest started.
imTest:3: attempt to call nil.
I can't figure out what is the reason for this, as a peek on the part of "bios.lua" where "os.loadAPI" is defined
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
seems to indicate that the API being loaded should have access to _G through the metatable. And as far as i can see _G should already contain "printTable" at the time of os.loadAPI("imTest") getting called.
Any insights are greatly appreciated!
Thanks,
hanno