Soviut
Soviut

Reputation: 91635

How can I get a function's name by its pointer in Lua?

In Lua I've created a pretty printer for my tables/objects. However, when a function is displayed, it's shown as a pointer.

I've been reading up on Lua Introspection but when I introspect the function with debug.getinfo() it won't return the function's name. This seems to be due to a scoping issue but I'm not sure how to get around it.

What is the best way to get a function's name using its pointer? (I understand functions are first class citizens in Lua and that they can be created anonymously, that's fine)

Upvotes: 3

Views: 5428

Answers (2)

etandel
etandel

Reputation: 381

For some reason, it seems to work only with number parameters (that is, active functions on the stack).

The script

function a() return debug.getinfo(1,'n') end
function prettyinfo(info) 
    for k,v in pairs(info) do print(k,v) end
end
prettyinfo(a())

prints

name    a
namewhat    global

but if I change the last line to

prettyinfo(debug.getinfo(a, 'n'))

it gives me only an empty string:

namewhat

Upvotes: 1

kikito
kikito

Reputation: 52698

when you create the functions, register them in a table, using them as keys.

local tableNames = {}

function registerFunction(f, name)
  tableNames[f] = name
end

function getFunctionName(f)
  return tableNames[f]
end

...
function foo()
  ..
end
registerFunction(foo, "foo")
...

getFunctionName(foo) -- will return "foo"

Upvotes: 4

Related Questions