As per the documentation(https://www.lua.org/manual/5.3/manual.html#lua_sethook), which says[empasise mine]:
Argument f is the hook function. mask specifies on which events the hook will be called: it is formed by a bitwise OR of the constants LUA_MASKCALL, LUA_MASKRET, LUA_MASKLINE, and LUA_MASKCOUNT. The count argument is only meaningful when the mask includes LUA_MASKCOUNT. For each event, the hook is called as explained below:
The call hook: is called when the interpreter calls a function. The hook is called just after Lua enters the new function, before the function gets its arguments.
The return hook: is called when the interpreter returns from a function. The hook is called just before Lua leaves the function. There is no standard way to access the values to be returned by the function.
The line hook: is called when the interpreter is about to start the execution of a new line of code, or when it jumps back in the code (even to the same line). (This event only happens while Lua is executing a Lua function.)
How to comprehend that lua_Hook is called when it jumps back in the code(This event only happens while Lua is executing a Lua function?
We can look at the source (Lua 5.4):
int luaG_traceexec (lua_State *L, const Instruction *pc) {
-- some parts removed
if (mask & LUA_MASKLINE) {
if (npci == 0 || /* call linehook when enter a new function, */
pc <= L->oldpc || /* when jump back (loop), or when */
changedline(p, pcRel(L->oldpc, p), npci)) { /* enter new line */
int newline = luaG_getfuncline(p, npci);
luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */
}
}
return 1; /* keep 'trap' on */
}
As can be seen, LUA_HOOKLINE is called in three cases: (1) enter a new function, (2) jump back (loop), or (3) enter new line.
"Enter new line" is checked by a call to changedline:
static int changedline (const Proto *p, int oldpc, int newpc) {
while (oldpc++ < newpc) {
if (p->lineinfo[oldpc] != 0)
return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc));
}
return 0; /* no line changes in the way */
}
This returns true if the new instruction is on a different line from the previous instruction.
luaG_getfuncline gets the line number for the instruction if there is debug information available. The function being checked is the active lua function based on the the current call info value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With