Lua global variable containing path to current file?

后端 未结 3 394
北荒
北荒 2021-01-12 15:37

Is there a global variable in Lua that contains the path to the file currently being interpreted? Something like Python\'s __file__ variable?

I ran a qu

相关标签:
3条回答
  • 2021-01-12 16:12

    In Lua 5.2, when a script is loaded via require, it receives as arguments the module name given to require and the filename that require used to open the script:

    $ cat a.lua
    require"b"
    $ cat b.lua
    print("in b",...)
    $ lua a.lua
    in b    b   ./b.lua
    

    In Lua 5.1, only the module name is passed, not the filename.

    0 讨论(0)
  • 2021-01-12 16:24

    In response to the answer by lhf:
    Being new to Lua, I was initially confused what ... meant. Turns out it's a vararg just like with ANSI C: https://www.lua.org/manual/5.3/manual.html#3.4. In my experience with lua 5.3, using

    local packageName, packagePath = ...
    

    got me the package name as when used in a require and the absolute file path of the package.

    0 讨论(0)
  • 2021-01-12 16:30

    The debug library has a getinfo method you can call, which can return, amongst other things, the source file for a function.

    local info = debug.getinfo(1,'S');
    print(info.source);
    

    That would return the name of the source file (which will begin with an @ symbol, indicating it is a filename) of the function at the first level of the call stack. By passing 1 you are asking for information about the current function. If you passed in 0 it would return =[C] as it would be returning information about the getinfo function itself.

    For more detailed information check out the Programming in Lua reference on the official Lua website: http://www.lua.org/pil/23.1.html

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