Reputation: 727
I have a simple lua code looks like below.
local function my_fun(x)
return nil, error("oops", 2)
end
local res, err = my_fun("foo")
print(res)
print(err)
print("finish")
What I expected is that the program can print until "finish", but I got the program exit. How should I do for just return the error instead of exit?
lua: test.lua:5: oops
stack traceback:
[C]: in function 'error'
test.lua:2: in local 'my_fun'
test.lua:5: in main chunk
[C]: in ?
Upvotes: 0
Views: 1020
Reputation: 2401
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.
Upvotes: 3