Lua does not have a runtime error/exception value. error does not return anything, instead it triggers a panic that unwinds the stack until caught.
You can catch such a panic with protected calls, using pcall(). pcall will return a boolean that is true when no error occurred and either the error or return value:
local function my_fun(x)
if x == "foo" then
error("oops")
-- notice the lack of return, anything after `error()` will never be reached
print("you will never see me")
end
return x
end
local ok, value = pcall(my_fun, "foo")
print(ok, value) -- prints "false, oops"
ok, value = pcall(my_fun, "bar")
print(ok, value) -- prints "true, bar"
Alternatively, you can define your own runtime error type. This could be as simple as just a string or as complex as an elaborate metatable-based class.
local function my_fun(x)
return nil, "oops" -- a simple string as 'error type'
end
-- alternatively
local function my_fun2(x)
return nil, debug.traceback("oops") -- also just a string, but includes a strack trace.
-- Note that generating a trace is expensive
end
local res, err = my_fun("foo")
print(res)
print(err)
print("finish")
Programming in Lua also has multiple chapters on error handling: https://www.lua.org/pil/8.3.html.
errorstops execution.