Say i have two files:
One is called mainFile.lua:
function altDoFile(name)
dofile(debug.getinfo(1).source:sub(debug.getinfo(1).source:find(".*\\")):sub(2)..name)
end
altDoFile("libs/caller.lua")
function callBack()
print "called back"
end
doCallback()
The other called caller.lua, located in a libs folder:
function doCallback()
print "performing call back"
_G["callBack"]()
end
The output of running the first file is then:
"performing call back"
Then nothing more, i’m missing a line!
Why is callBack never getting executed? is this intended behavior, and how do i get around it?
The fact that the function is getting called from string is important, so that can’t be changed.
UPDATE:
I have tested it further, and the _G[“callBack”] does resolve to a function (type()) but it still does not get called
Why not just use dofile?
It seems that the purpose of
altDoFileis to replace the running script’s filename with the script you want to call thereby creating an absolute path. In this case the path forcaller.luais a relative path so you shouldn’t need to change anything for Lua to load the file.Refactoring your code to this:
Seems to give the result you are looking for:
Just as a side note,
altDoFilethrows an error if the path does not contain a\character. Windows uses the backslash for path names, but other operating systems like Linux and MacOS do not.In my case running your script on Linux throws an error because
string.findreturns nill instead of an index.If you need to know the working path of the main script, why not pass it as a command line argument:
Then in Lua: