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 quick for k, v in pairs(_G) do print(k) end
in the interpreter to see if I could find anything. Only the following variables were listed?
string xpcall package tostring print os unpack require getfenv setmetatable next assert tonumber io rawequal collectgarbage getmetatable module rawset math debug pcall table newproxy type coroutine _G select gcinfo pairs rawget loadstring ipairs _VERSION dofile setfenv load error loadfile
Any suggestions on how to get the path the file currently being executed?
Syntax. The syntax for declaring a global variable in Lua is pretty straightforward, just declare whatever name you want to use for your variable and assign a value to it. It should be noted that we cannot declare a global variable without assigning any value to it, as it is not something that Lua allows us to do.
Lua offers a higher-level function to load and run libraries, called require . Roughly, require does the same job as dofile , but with two important differences. First, require searches for the file in a path; second, require controls whether a file has already been run to avoid duplicating the work.
Lua modules and packages - what you need to know As with most search paths, the LUA_PATH is actually a semicolon-separated collection of filesystem paths. Lua scans them in the order they are listed to find a module. If the module exists in multiple paths, the module found first wins and Lua stops searching.
And Lua will now search for modules in the lib directory (in addition to where it usually does). You can also use the LUA_PATH environment variable to do this before even starting Lua.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With