Lua中的Hook机制

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: "call", "return", "line", or "count". 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, we call 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 (`c´, `r´, or `l´) in the mask string. To monitor the count event, we simply supply a counter as the third argument. To turn off hooks, we call 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 print as the hook function and instructs Lua to call it only at line events. A more elaborated tracer can use getinfo to 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")


你可能感兴趣的:(LUA)