whiteblXK
whiteblXK

Reputation: 137

Getting current file name in Lua

How to get current file name without path and .lua?

I tried with:

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

and this is what I get:

@data/spells/scripts/10lvl/bakurichimacha.lua
@data/spells/scripts/1000lvl/brave sword attack.lua

How to delete these parts:

@data/spells/scripts/10lvl/ and .lua
@data/spells/scripts/1000lvl/ and .lua

To print just bakurichimacha and brave sword attack?

Upvotes: 4

Views: 20072

Answers (3)

Soham Mahajan
Soham Mahajan

Reputation: 69

Though the accepted @kingjulian answer seems to be working in most of the cases , it fails for pathless filename arguments. Eg. aTestFile.lua etc.

I have modified the regex a bit to include these missing scenarios

function get_file_name(file)
      return file:match("[^/]*.lua$")
end

tested here

To get the only file name excluding extension .lua

function get_file_name(file)
      local file_name = file:match("[^/]*.lua$")
      return file_name:sub(0, #file_name - 4)
end

Upvotes: 6

Valentin Borisov
Valentin Borisov

Reputation: 770

You can use string.match function

local filename = function()
  local str = debug.getinfo(2, "S").source:sub(2)
  return str:match("^.*/(.*).lua$") or str
end
print(filename());

Upvotes: 5

kingJulian
kingJulian

Reputation: 6170

Try this:

function get_file_name(file)
      return file:match("^.+/(.+)$")
end

Upvotes: 4

Related Questions