This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The third edition targets Lua 5.2 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.
|Programming in Lua|
|Part III. The Standard Libraries Chapter 23. The Debug Library|
The hook mechanism of the debug library allows us
to register a function that will be called at
specific events as your program runs.
There are four kinds of events that can trigger a hook:
call events happen every time Lua calls a function;
return events happen every time a function returns;
line events happen when Lua starts executing a new line of code;
and count events happen after a given number of instructions.
Lua calls hooks with a single argument,
a string describing the event that generated the call:
Moreover, for line events, it also passes a second argument,
the new line number.
We can always use
debug.getinfo to get more information
inside a hook.
To register a hook,
debug.sethook with two or three arguments:
The first argument is the hook function;
the second argument is a string that
describes the events we want to monitor;
and an optional third argument is a number
that describes at what frequency we want to get count events.
To monitor the call, return, and line events,
we add their first letters (`
r´, or `
in the mask string.
To monitor the count event,
we simply supply a counter as the third argument.
To turn off hooks,
sethook with no arguments.
As a simple example, the following code installs a primitive tracer, which prints the number of each new line the interpreter executes:
debug.sethook(print, "l")It simply installs
getinfoto add the current file name to the trace:
function trace (event, line) local s = debug.getinfo(2).short_src print(s .. ":" .. line) end debug.sethook(trace, "l")
|Copyright © 2003–2004 Roberto Ierusalimschy. All rights reserved.|