Lua中巧妙的获取函数的参数个数

function getArgs(fun)
    local args = {}
    local hook = debug.gethook()
    local argHook = function(...)
        local info = debug.getinfo(3)
        for k,v in pairs(info) do
        	print(k,v)
        end
        if "pcall" ~= info.name then
            return
        end
        for i = 1, math.huge do
            local name, value = debug.getlocal(2, i)
            print(i, name, value)
            if "(*temporary)" == name then
                debug.sethook(hook)
                error("")
                return
            end
            table.insert(args, name)
        end
    end
    debug.sethook(argHook, "c")
    pcall(fun)
    return args
end

function test(a, b, c)
	print(a,b,c)
end


local t = getArgs(test)
for k,v in pairs(t) do
	print(k,v)
end

  

posted @ 2018-12-03 14:11  紫——瞳  阅读(1960)  评论(0编辑  收藏  举报