lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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.

The idea with 'doc' is that a documentation generator might fill in additional information about the functions (such as their names, return values, notes, etc) obtained by parsing the source file. (The format could be changed of course. This is just a simple example.)

C functions only give "..." as their arguments, since there's no way to know what they'll do with the stack. This would have to be solved by parsing as well.

--
Sent from my Game Boy.