Q: create a hookfunction in lua

Viewed 1195

I want do a hookfunction for lua :

For explain i want hook the params and return the params when function called, like this :

function func1(x, y)
  print(tonumber(x) + tonumber(y))
end

a = hookfunction(func1, function(...)    -- a = old function
  local args = { ... }
  print("Argument 1 =>", args[1])
  print("Argument 2 =>", args[2])
  return a(...)
end)

func1(12, 5)
Output : 

Argument 1 => 12
Argument 2 => 5
17
2 Answers

There's two different things you can do. You can either create a wrapper just for that function, or you can actually set a debugging hook in the Lua runtime. Here's how you'd create a wrapper:

function func1(x, y)
  print(tonumber(x) + tonumber(y))
end

function wrapfunction(a)    -- a = old function
  return function(...)
    local args = { ... }
    print("Argument 1 =>", args[1])
    print("Argument 2 =>", args[2])
    return a(...)
  end
end
func1 = wrapfunction(func1)

func1(12, 5)

And here's how you'd set a debugging hook:

function func1(x, y)
  print(tonumber(x) + tonumber(y))
end

function hookfunction(event)
  if debug.getinfo(2, 'f').func == func1 then
    print("Argument 1 =>", select(2, debug.getlocal(2, 1)))
    print("Argument 2 =>", select(2, debug.getlocal(2, 2)))
  end
end
debug.sethook(hookfunction, 'c')

func1(12, 5)

You can try this

function func1(x, y)
  print(tonumber(x) + tonumber(y))
end

oldfunc1 = func1

function func1hook(x, y)
  print("Argument x =>", x)
  print("Argument y =>", y)
  return oldfunc1(x, y)
end

func1 = func1hook

func1(4,4)

I'm not sure it works for C functions but you can try. If you want more universal hookfunction it's also possible.

https://www.lua.org/cgi-bin/demo

Related