Get containing path of lua file

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

    I have written a function getScriptDir which uses the debug information like a few other people have suggested, but this one is going to work everytime (at least in Windows). But the thing is there are quite a few lines of code as it uses another function string.cut which i have created, which separates a string every given pattern, and puts it into a table.

    function string.cut(s,pattern)
      if pattern == nil then pattern = " " end
      local cutstring = {}
      local i1 = 0
      repeat
        i2 = nil
        local i2 = string.find(s,pattern,i1+1)
        if i2 == nil then i2 = string.len(s)+1 end
        table.insert(cutstring,string.sub(s,i1+1,i2-1))
        i1 = i2
      until i2 == string.len(s)+1
      return cutstring
    end
    
    function getScriptDir(source)
      if source == nil then
        source = debug.getinfo(1).source
      end
      local pwd1 = (io.popen("echo %cd%"):read("*l")):gsub("\\","/")
      local pwd2 = source:sub(2):gsub("\\","/")
      local pwd = ""
      if pwd2:sub(2,3) == ":/" then
        pwd = pwd2:sub(1,pwd2:find("[^/]*%.lua")-1)
      else
        local path1 = string.cut(pwd1:sub(4),"/")
        local path2 = string.cut(pwd2,"/")
        for i = 1,#path2-1 do
          if path2[i] == ".." then
            table.remove(path1)
          else
            table.insert(path1,path2[i])
          end
        end
        pwd = pwd1:sub(1,3)
        for i = 1,#path1 do
          pwd = pwd..path1[i].."/"
        end
      end
      return pwd
    end
    

    Note: if you want to use this function in another OS than Windows, you have to change the io.popen("echo %cd%") in the line 15 to whatever command gives you present working directory in your OS, e.g. io.popen("pwd") for Linux, and the pwd2:sub(2,3) == ":/" in the line 18 to whatever represents the root directory in your OS, e.g. pwd2:sub(1,1) == "/" for Linux.

    Note2: if you don't provide the source variable to the function via debug.getinfo(1).source when calling it, then it will return the path to the directory of the file containing this function. Therefore, if you want to get the directory of a file which you called via dofile or loadfile, you will have to give it the source, like this: getScriptDir(debug.getinfo(1).source).

提交回复
热议问题