🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Debug Tracebacks

A debug traceback is a string that lists the calls leading to a point in a program. The debug library builds it, but you never print it whole.

A traceback is a string with your message

Ask for the type of the result. Then check that your message is inside it.

local function boom()
  return debug.traceback("oops")
end
local tb = boom()
print(type(tb))
print(string.find(tb, "oops") ~= nil)

Check a phrase that is always present

Every traceback carries the same heading phrase. A search for an absent word gives false.

local function boom()
  return debug.traceback("oops")
end
local tb = boom()
print(string.find(tb, "stack traceback") ~= nil)
print(string.find(tb, "zzzmissing") ~= nil)

A traceback follows nested calls

The outer function calls the inner one. The message still shows up in the result.

local function inner()
  return debug.traceback("deep")
end
local function outer()
  return inner()
end
local tb = outer()
print(string.find(tb, "deep") ~= nil)
print(string.find(tb, "stack traceback") ~= nil)

Example

local function failHere()
  return debug.traceback("bad value")
end
local function run()
  return failHere()
end
local tb = run()
print(type(tb))
print(string.find(tb, "bad value") ~= nil)
print(string.find(tb, "stack traceback") ~= nil)
print(string.find(tb, "zzzmissing") ~= nil)

Key points

  • Use debug.traceback to get the traceback as a string.
  • The string starts with your message when you pass one.
  • Test the string with string.find instead of printing it.
  • Compare a find result with nil to turn it into a true or false answer.
  • A traceback shows a local function by its file and line, not by its name.

In this example, run calls failHere, and failHere builds a traceback with the message bad value. The checks show the result is a string, the message is present, and the heading phrase is present. The last check shows an absent word is not present.

Note

A traceback carries file and line details, so only its stable phrases are worth checking.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How should you check what a traceback contains?