Lua Error Objects
An error object is a value of any type that error raises to report a failure. It can be a string, or a table carrying a code and a message.
A table error carries a code and a message
The failing function raises a table, not a string. The caller reads the two fields from that table.
local function fail()
error({code = 404, message = "not found"})
end
local ok, err = pcall(fail)
print(ok)
print(err.code, err.message)Level 0 is bare and level 1 adds a position
Level 0 gives the bare message. Level 1 adds the position of its own error line, which is line 5 here.
local function fail0()
error("boom", 0)
end
local function fail1()
error("boom", 1)
end
local _, e0 = pcall(fail0)
local _, e1 = pcall(fail1)
print(e0)
print(string.match(e1, ":(%d+):"))Level 2 reports the caller line
Level 2 skips the error line and reports the caller. The printed number is the line where outer calls inner.
local function inner()
error("boom", 2)
end
local function outer()
inner()
end
local _, err = pcall(outer)
print(string.match(err, ":(%d+):"))Example
local function check(amount)
if amount < 0 then
error({code = "NEG", message = "negative not allowed"})
end
return amount * 2
end
local ok1, value1 = pcall(check, 5)
local ok2, err2 = pcall(check, -3)
print(ok1, value1)
print(ok2)
print(err2.code, err2.message)Key points
- Any value: error can raise a string, a number, or a table, not only a message string.
- Table error: a table error can carry a code field and a message field for the caller to read.
- Caller reads fields: pcall returns the table, so the caller can print its code and message fields separately.
- Level zero: error with level 0 reports the bare value with no position added.
- Level one: error with level 1 reports the position where error was called.
- Level two: error with level 2 reports the position of the caller of the function that called error.
In this example, check doubles a good amount and raises a table error for a negative amount. The first pcall returns true and 10, the second returns false, and the caller reads the code and message fields from the table.
Note
check the error value itself, because a position string changes with the file and line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A function raises a table with code 404 and message "not found". What does pcall give the caller as its second return value?