This is a trick I saw in the Dolphin emulator. I'm a bit surprised it's not more known. (At least, I've never seen it elsewhere.)
#!/usr/bin/env lua
local doc = {}
local function get_func_info(func)
local info = debug.getinfo(func, 'u')
local nparams = info.nparams
local params = {}
for i = 1, nparams do
params[i] = debug.getlocal(func, i)
end
if info.isvararg then params[#params+1] = '...' end
return 'function(' .. table.concat(params, ', ') .. ')' ..
(doc[func] or '')
end
local meta = debug.getmetatable(get_func_info)
if not meta then
meta = {}
debug.setmetatable(get_func_info, meta)
end
function meta:__tostring()
return get_func_info(self)
end
local x = 1
function f(a, b, c, ...) return x end
--example use of 'doc' to add additional information such as returns
doc[get_func_info] = " -> string"
doc[f] = " -> number"
print(get_func_info)
print(f)
print(print)
This gives output like:
function(func) -> string
function(a, b, c, ...) -> number
function(...)
which is a little more useful than the default behaviour. Unfortunately it doesn't provide the function's address anymore (maybe some code used that to uniquely identify functions or perform black magic) since there's no "rawtostring" function.