Calling back to a main file from a dofile in lua -


say have 2 files:

one 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 libs folder:

function docallback()     print "performing call back"     _g["callback"]() end 

the output of running first file then:

"performing call back" 

then nothing more, i'm missing line!

why callback never getting executed? intended behavior, , how around it?

the fact function getting called string important, can't changed.

update: have tested further, , _g["callback"] resolve function (type()) still not called

why not use dofile?

it seems purpose of altdofile replace running script's filename script want call thereby creating absolute path. in case path caller.lua relative path shouldn't need change lua load file.

refactoring code this:

dofile("libs/caller.lua")  function callback()     print "called back" end  docallback() 

seems give result looking for:

$ lua mainfile.lua  performing call called 

just side note, altdofile throws error if path not contain \ character. windows uses backslash path names, other operating systems linux , macos not.

in case running script on linux throws error because string.find returns nill instead of index.

lua: mainfile.lua:2: bad argument #1 'sub' (number expected, got nil) 

if need know working path of main script, why not pass command line argument:

c:\luafiles> lua mainfile.lua c:/luafiles 

then in lua:

local working_path = arg[1] or '.' dofile(working_path..'/libs/caller.lua') 

Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -