Get containing path of lua file

Viewed 42579

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 entirely different. I know luafilesystem will let me get the current working directory, but it doesn't seem to be able to tell the current executing script file.

Thanks

EDIT: I'm not running from the standard command line interpreter, I am executing the scripts from a C++ binary via luabind.

10 Answers

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)

If you want the real path including the filename, just use the following

pathWithFilename=io.popen("cd"):read'*all'
print(pathWithFilename)

Tested on Windows.

Explanation:

io.popen - Sends commands to the command line, and returns the output.

"cd" - when you input this in cmd you get the current path as output.

:read'*all' - as io.popen returns a file-like object you can read it with the same kind of commands. This reads the whole output.


If someone requires the UNC path:

function GetUNCPath(path,filename)
local DriveLetter=io.popen("cd "..path.." && echo %CD:~0,2%"):read'*l'
local NetPath=io.popen("net use "..DriveLetter):read'*all'
local NetRoot=NetPath:match("[^\n]*[\n]%a*%s*([%a*%p*]*)")
local PathTMP=io.popen("cd "..path.." && cd"):read'*l'
PathTMP=PathTMP:sub(3,-1)
UNCPath=NetRoot..PathTMP.."\\"..filename
return UNCPath
end
Related