0

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 ?
1
  • The traceback tells you that calling error stops execution. Commented Oct 31, 2022 at 10:51

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.