Lua Debugging Guide — Debug Library and Diagnostic Techniques
In this tutorial, you will learn about Lua Debugging Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
Lua debug library is an interface to the Lua virtual machine's introspection and debugging facilities -- supporting hooks for line, call, and return events, plus functions to inspect the call stack, local variables, and upvalues.
Debug Hooks
-- Hook on every line
debug.sethook(function(event)
if event == "line" then
local info = debug.getinfo(2)
print("Line:", info.currentline)
end
end, "l")
-- Hook on calls
debug.sethook(function(event)
if event == "call" then
print("Calling function:", debug.getinfo(2).name)
end
end, "c")
Inspecting the Stack
function inner()
print(debug.traceback())
end
function outer()
inner()
end
outer()
-- Prints full call stack
Inspecting Variables
function foo(a, b)
local c = a + b
-- List local variables at level 2
local i = 1
while true do
local name, value = debug.getlocal(2, i)
if not name then break end
print(name, "=", value)
i = i + 1
end
end
foo(3, 4)
--> a = 3, b = 4, c = 7
Common Mistakes
1. Forgetting to remove hooks
Hooks impact performance. Remove hooks after debugging with debug.sethook() (no arguments clears hooks).
2. Using debug in production
The debug library is slow and exposes internals. Remove debug calls from production code.
3. Relying on line numbers from debug.getinfo
Line numbers can change with edits. Use function names for identification when possible.
Practice Questions
1. How do you trace all function calls?
Use debug.sethook(function(e) if e=="call" then print(debug.getinfo(2).name) end end, "c").
2. How do you get a stack trace?
Call debug.traceback() which returns a string describing the call stack.
3. When should you NOT use the debug library? In production code. It slows execution and exposes implementation details.
FAQ
{{< faq question="Can I modify local variables with the debug library?" >}}
Yes. debug.setlocal(level, index, value) changes the value of a local variable at the given stack level.
{{< /faq >}}
{{< faq question="Does the debug library work with LuaJIT?" >}} Partially. LuaJIT supports most debug functions but some features like hooks may behave differently or be slower. {{< /faq >}}
{{< faq question="How do I get the current line number?" >}}
debug.getinfo(1).currentline returns the line number of the currently executing instruction.
{{< /faq >}}
What's Next
Now learn about error handling in Lua.
| Topic | Description | Link |
|---|---|---|
| Error Handling | pcall, xpcall, error handling | {{< ref "23-error-handling" >}} |
| OOP Advanced | Advanced OOP patterns | {{< ref "24-oop-advanced" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro