Get containing path of lua file

后端 未结 10 1958
粉色の甜心
粉色の甜心 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:22

    The only reliable way to get what you want is to replace dofile with your own version of this function. Even the debug.getinfo method won't work, because it will only return the string passed to dofile. If that was a relative path, it has no idea how it was converted to an absolute path.

    The overriding code would look something like this:

    local function CreateDoFile()
        local orgDoFile = dofile;
    
        return function(filename)
            if(filename) then --can be called with nil.
                local pathToFile = extractFilePath(filename);
                if(isRelativePath(pathToFile)) then
                    pathToFile = currentDir() .. "/" .. pathToFile;
                end
    
                --Store the path in a global, overwriting the previous value.
                path = pathToFile; 
            end
            return orgDoFile(filename); --proper tail call.
        end
    end
    
    dofile = CreateDoFile(); //Override the old.
    

    The functions extractFilePath, isRelativePath, and currentDir are not Lua functions; you will have to write them yourself. The extractFilePath function pulls a path string out of a filename. isRelativePath takes a path and returns whether the given path is a relative pathname. currentDir simply returns the current directory. Also, you will need to use "\" instead of "/" on Windows machines.

    This function stores the path in a global called path. You can change that to whatever you like.

提交回复
热议问题