Get containing path of lua file

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

    If the Lua script is being run by the standard command line interpreter, then try arg[0].

    0 讨论(0)
  • 2021-02-12 12:14

    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())
    
    0 讨论(0)
  • 2021-02-12 12:14
    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'
    
    0 讨论(0)
  • 2021-02-12 12:14

    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)
    
    0 讨论(0)
  • 2021-02-12 12:16

    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.

    0 讨论(0)
  • 2021-02-12 12:17

    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

    0 讨论(0)
提交回复
热议问题