More on Debugging

Last time I started looking into how to debug Lua code and discovered it's really a form of introspection and doesn't feel, to me, like true debugging. Today, I'll continue looking at this capability.
I learned about using the debug library and debug.getinfo and debug.getlocal to examine functions to return information on how and where functions and local variables are used.

debug.sethook


Additionally, Lua's debug library allows you to set something known as a "hook" which is an event handler to monitor running code. You can set three types of hook:

  • return: called each time function exits (returns).
  • call : called each time a function is called.
  • line: called every time a new line of code is executed.

This feels, to me, to be closer to what I think of when I hear someone say "debugging".


In order to set a hook, you need to call debug.sethook.

debug.setehook(function,first letter of the hook type)

The function is the name of the function to be called when the hook executes, and the second parameter is the first letter of the hook. For example if you pass in "l", you will be setting a line hook.

You clear a hook by calling debug.sethook


line Hook



The hook function needs to accept two parameters:

function x(event, line)

Here is an example of how to use it:
Screen Shot 2021-05-18 at 8.10.33 AM

And here is what happens when you run this:

Screen Shot 2021-05-18 at 8.11.34 AM




call Hook



The hook function for call requires only a single parameter. This is what happens when I execute (again with my test function.


Screen Shot 2021-05-18 at 8.30.47 AM

Screen Shot 2021-05-18 at 8.31.54 AM



return Hook



The return hook function also takes a single parameter. I bet I can figure out what it will return: "return".



Screen Shot 2021-05-18 at 8.37.11 AM

Screen Shot 2021-05-18 at 8.37.41 AM

I was right, even though there is less output because the execution only hit a single return point.

The Power



That's not very useful is it? It just returns a single string. By its own, no, it isn't. But remember, the power of the hook is in what you do in the hook function. I didn't do anything except print the parameters. I could, for example, call debug.callinfo() to introspect the line or function the hook "trapped" in.

This feels more like debugging, but it's still not what I want to use to find a problem in my code. I'd have to find the problems in my hook functions first. That's still too much work for me.

That's enough for today.

This site does not track your information.