Page 1 of 1

Can I get the path to the current file?

Posted: Sat Feb 20, 2021 12:24 pm
by Pi-C
Is there a way to get the name of and path to the file that is currently processed, so I can log it?

Use case: I'm cleaning up the data*lua files of BI, moving out compatibility code for other mods to external files. There are a lot of files with similar names (e.g. "updates/mod_name.lua" and "final-fixes/mod_name.lua"), and I've moved files between folders several times. In order to check that I didn't forget to require a file, I want to output the file path and name whenever a file is entered. Using fixed strings for that is not an option because I may forget to change the message text after moving or renaming a file.

I know that something like this would work:

Code: Select all

if not BI.check_mods("alien-biomes") then
  log("Nothing to do!")
  return
end
log() automatically adds path, filename, and even the line number to the output. However, I've made a wrapper that will only write to the log in my mod's debugging mode, as I don't want to spam the log unnecessarily. The problem is that all output will be preceded by path + name of the file containing the wrapper function, so that information is basically useless. Therefore, I'd like to find a way to do something like this:

Code: Select all

if not BI.check_mods("alien-biomes") then
  log_wrapper(get_current_file_name() .. ": Nothing to do!")
  return
end
Is that possible somehow?

Re: Can I get the path to the current file?

Posted: Sat Feb 20, 2021 12:50 pm
by Pi-C
For clarification: I'm in no way interested in the absolute path of the file on the OS's file system, but in the path relative to the root of my mod. :-)

Re: Can I get the path to the current file?

Posted: Sat Feb 20, 2021 1:33 pm
by DaveMcW

Code: Select all

local tmp = 1
log(debug.getinfo(tmp).source)

Re: Can I get the path to the current file?

Posted: Sat Feb 20, 2021 2:11 pm
by eradicator
DaveMcW wrote: Sat Feb 20, 2021 1:33 pm

Code: Select all

local tmp = 1
log(debug.getinfo(tmp).source)
No need to define temporary variables, you can just give a numeric level - in case of a seperate function handling this probably "2". See also erlibs Log module.

Re: Can I get the path to the current file?

Posted: Sat Feb 20, 2021 2:30 pm
by Pi-C
DaveMcW wrote: Sat Feb 20, 2021 1:33 pm

Code: Select all

local tmp = 1
log(debug.getinfo(tmp).source)
Thanks, exactly what I've been looking for! That will make it easy to use a file as a template.
eradicator wrote: Sat Feb 20, 2021 2:11 pm No need to define temporary variables, you can just give a numeric level - in case of a seperate function handling this probably "2". See also erlibs Log module.
Thanks! I believe the local variable was only defined to indicate that the argument to debug.getinfo() can be … variable … So I checked the Lua reference manual for what arguments are allowed, and used the proper value. :-)