Get containing path of lua file

后端 未结 10 1943
粉色の甜心
粉色の甜心 2021-02-12 12:00

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

10条回答
  •  终归单人心
    2021-02-12 12:21

    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
    

提交回复
热议问题