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.

23 – The Debug Library

The debug library does not give you a debugger for Lua, but it offers all the primitives that you need for writing a debugger for Lua. For performance reasons, the official interface to these primitives is through the C API. The debug library in Lua is a way to access these functions directly within Lua code. This library declares all its functions inside the debug table.

Unlike the other libraries, you should use the debug library with parsimony. First, some of its functionality is not exactly famous for performance. Second, it breaks some sacred truths of the language, such as that you cannot access a local variable from outside the function that created it. Frequently, you may not want to open this library in your final version of a product, or else you may want to erase it:

    debug = nil

The debug library comprises two kinds of functions: introspective functions and hooks. Introspective functions allow us to inspect several aspects of the running program, such as its stack of active functions, current line of execution, and values and names of local variables. Hooks allow you to trace the execution of a program.

An important concept in the debug library is the stack level. A stack level is a number that refers to a particular function that is active at that moment, that is, it has been called and has not returned yet. The function calling the debug library has level 1, the function that called it has level 2, and so on.