tags:

views:

104

answers:

5

Something like this:

function foo()
    print( __func__ )
   ...
end

How can it be done?

+1  A: 

Use the Debug Library. It provides a getinfo(func) function that returns a table with information about the function.

schot
+5  A: 

You can't. In lua, functions are first class variables. So they don't have names. You might as well ask "what the name of 2" is. Just because some variable was assigned the value '2' doesn't make that variable the name of 2. Likewise "someFunc" is a variable - potentially one of many - that holds a particular function.

Chris Becke
+7  A: 
#!/usr/bin/lua

local function myFunc()
 print(debug.getinfo(1, "n").name);
end
myFunc()
Ephraim
+1  A: 

While I agree with Ephraim's answer, that code will not always report the same name as pointed out by Chris Becke. When the function is assigned to another variable, the "name" would be changed.

Here is another alternative. It just uses a string to identify the function. This method solves the changing name problem, but introduces a maintenance issue. The string would need to be kept in sync with the function name with future refactorization.

function foo()
  local __func__ = "foo"
  print( __func__ )
  --...
end

Alternatively, if the location of the function is more important than the name, the following may be better. It will give a name to the function that is based on the source and line number.

function getfunctionlocation()
  local w = debug.getinfo(2, "S")
  return w.short_src..":"..w.linedefined
end

function foo()
  print(getfunctionlocation()) --> foo.lua:6
  --...
end

If the __func__ still seems better, and standard Lua is not important, then the Lua parser can be modified as it is in this example for __FILE__ and __LINE__.

gwell
+1  A: 

Functions don't necessarily have them. It's perfectly legal in Lua to create anonymous functions with no name- and call it, without assigning it one.

(function()
    print("in anonymous function!")
end)()

Is perfectly valid Lua. What name do you want to give that function?

DeadMG