Lobster
Lobster

Reputation: 635

How to get name of the function

I have a problem. How to know the name of the function that called my function without using the debug namespace. For example:

function test1()
   test2()
end

function test2()
   --How to get here name of function which have called my function test2.
   --How to get here "test1"?
end

It's will be easy if I will be allow to use debug namespace, but I can use. Have anyone any idea? Sorry for my English.

Upvotes: 2

Views: 3136

Answers (2)

Wref
Wref

Reputation: 58

This doesn't solve half of your problem, but you can give your functions names with FuncTables. Whether you can use this to help solve your problem, I don't know.

-- create a functable --

functable = {name = "bob"}
metatable = {}

metatable.__call = function()
    print "you just called a table!"
end

setmetatable(functable,metatable)

-- call a functable and get it's name --

functable()
print(functable.name)

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 474316

Functions do not have names. Functions are values in Lua, just like the number 5.23, or the string "string". Those are values, and they can be stored in many places. Therefore, there is no real name for a function. The Debug system assigns functions names based on how they were initially declared, but that's about it.

If a function needs to know who called it, then it is the responsibility of that function to take the caller as a function parameter.

Upvotes: 5

Related Questions