1

In this answer, a method is provided for inspecting the signature of a Lua function. The answer notes that:

This algorithm works with Lua 5.2. Older versions would be similar but not the same:

What would the equivalent be in Lua 5.1?

AnandA777
  • 33
  • 5
  • The linked answer is almost correct in Lua 5.1. The only difference is with the vararg. The signature `function (x,y,...)` will be displayed as `function (x,y,arg)`. Is it critical for you? – Egor Skriptunoff Jun 29 '18 at 10:26

1 Answers1

2
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

Usage:

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

print(funcsign(somefunc))
Egor Skriptunoff
  • 906
  • 1
  • 8
  • 23