debug.sethook

Sets a debug hook function

Prototype

debug.sethook (thread, f, mask, count)

Description

Sets the function f as a hook to be called when the "mask" condition is satisfied.

If count is non-zero, it is called after every "count" instructions.

The thread argument is optional and defaults to the current thread.

If called without arguments, turns off the hook.

Mask can be one or more of: The mask can be the empty string if you simply want to hook after "count" instructions.

The function f is called with its first parameter being a string, which can be one of: In the case of "line" events it gets a second parameter, being the new line number.

Inside the hook you can use debug.getinfo with level 2 to find information about the running function. (Level 0 is getinfo, and level 1 is the hook function). In the case of "tail return" however debug.getinfo will not return valid information.

Here is an example of setting a hook to stop a runaway function from executing for too long:

function test ()
  a = 0
  for i = 0, 1000 do
    a = a + i
  end -- for
end -- test

function hook (why)
  error ("hook reached: " .. why)
end -- hook

debug.sethook (hook, "", 100)

test () --> error:  hook reached: count
In this case, the hook stopped execution after 100 instructions.

This second example uses a "call" hook to display when each new function is entered:

function f ()
  function g ()
  end -- g

 g () 
 g ()
end -- f

function hook (why)
  print ("hook reached: ", why)
  print ("function =", debug.getinfo (2, "n").name)
end -- hook

debug.sethook (hook, "c", 0)

f ()

 -->
 
hook reached:  call
function = f
hook reached:  call
function = g
hook reached:  call
function = g

Lua functions

Topics