4
votes

I have written a Lua script that uses the debug API (debug.sethook) to hook calls and returns. I use it to print out a nicely formatted call tree - which is very useful for debugging.

In the hook handler function I increment or decrement a global indentLevel variable based on whether the event is 'call' or 'return' (or 'tail return'). I then use debug.getinfo to get info about the calling function and dump it to stdout at the current indent level.

For 'call' events I would like to also print out the parameter values that were passed to the particular call. Presumably I could do this in a C/C++ implementation of the hook handler function by looking at the Lua stack.

Does anyone know if there is a way to determine the parameter values from within the debug handler function in Lua?

1

1 Answers

1
votes

I think what you need is debug.getlocal. From the manual:

This function returns the name and the value of the local variable with index local of the function at level level of the stack. (The first parameter or local variable has index 1, and so on, until the last active local variable.) The function returns nil if there is no local variable with the given index, and raises an error when called with a level out of range. (You can call debug.getinfo to check whether the level is valid.)

Variable names starting with '(' (open parentheses) represent internal variables (loop control variables, temporaries, and C function locals).

I haven't tried this myself, but it looks like it should reveal what you need to know. One thing that doesn't leap out at me from the documentation is how to determine how many parameters were actually passed, but that might be among the trivia revealed by debug.getinfo.