【问题标题】:Inspect function signature in Lua 5.1检查 Lua 5.1 中的函数签名
【发布时间】:2018-12-08 06:03:40
【问题描述】:

this answer 中,提供了一种检查Lua 函数签名的方法。答案指出:

此算法适用于 Lua 5.2。旧版本会相似但不一样:

Lua 5.1 中的等价物是什么?

【问题讨论】:

  • 链接的答案在 Lua 5.1 中几乎是正确的。唯一的区别是可变参数。签名function (x,y,...) 将显示为function (x,y,arg)。这对你来说很重要吗?

标签: reflection lua lua-5.1


【解决方案1】:
function funcsign(f)
   assert(type(f) == 'function', "bad argument #1 to 'funcsign' (function expected)")
   local p = {}
   pcall(
      function()
         local oldhook
         local delay = 2
         local function hook(event, line)
            delay = delay - 1
            if delay == 0 then
               for i = 1, math.huge do
                  local k, v = debug.getlocal(2, i)
                  if type(v) == "table" then
                     table.insert(p, "...")
                     break
                  elseif (k or '('):sub(1, 1) == '(' then
                     break
                  else
                     table.insert(p, k)
                  end
               end
               if debug.getlocal(2, -1) then
                  table.insert(p, "...")
               end
               debug.sethook(oldhook)
               error('aborting the call')
            end
         end
         oldhook = debug.sethook(hook, "c")
         local arg = {}
         for j = 1, 64 do arg[#arg + 1] = true end
         f((table.unpack or unpack)(arg))
      end)
   return "function("..table.concat(p, ",")..")"
end

用法:

local function somefunc(a, b, c, ...)
   return 
end

print(funcsign(somefunc))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2011-11-26
    • 2021-10-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多