I am wondering if there is a way of getting the path to the currently executing lua script file?
This is specifically not the current working directory, which could be
If the Lua script is being run by the standard command line interpreter, then try arg[0]
.
This is a more elegant way:
function script_path()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
print(script_path())
arg[0]:match('.*\\')
If it returns nil try changing the .\*\\\
with .*/
and arg[0]
with debug.getinfo(1).short_src
.
But I find this to be the best and shortest way to get the current directory.
You can of course append the file you are looking for with the ..
operator. It will look something like this:
arg[0]:match('.*\\')..'file.lua'
if you want the actual path :
path.dirname(path.abspath(debug.getinfo(1).short_src))
else use this for full file path :
path.abspath(debug.getinfo(1).short_src)
Have a look at the Lua debug library, which is part of the standard Lua distribution. You can use debug.getinfo to find the current file, or the file up N frames on the call stack:
http://www.lua.org/manual/5.1/manual.html#5.9
Note that this is probably fairly slow, so it is not something you want to do on the fast path if you are worried about such things.
As lhf says:
~ e$ echo "print(arg[0])" > test.lua
~ e$ lua test.lua
test.lua
~ e$ cd /
/ e$ lua ~/test.lua
/Users/e/test.lua
/ e$
Here's the same info using the debug.getinfo mechanism
~ e$ echo "function foo () print(debug.getinfo(1).source) end; foo()" > test.lua
~ e$ lua test.lua
@test.lua
~ e$ cd /
/ e$ lua ~/test.lua
@/Users/e/test.lua
/ e$
This is available from the C API lua_getinfo