1

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)

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • 2
    See this question: http://stackoverflow.com/questions/4021816/ – sbk Jan 15 '12 at 00:23
  • I was hoping to do it without having to actually modify the functions. I wanted to get the function name for my table printer. – Soviut Jan 15 '12 at 01:42

2 Answers2

4

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"
kikito
  • 51,734
  • 32
  • 149
  • 189
  • 3
    @Soviut I was going to respond with something like this too. Teeeeechnically speaking, Lua functions do not have names. When you enter `function foo()`, it is the same as doing `foo = function()`. In other words, the function is a free agent that just happens to have a variable named `foo` pointing to it. – TheBuzzSaw Jan 15 '12 at 17:04
1

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
etandel
  • 381
  • 3
  • 4