【问题标题】:How do Lua return an error without end of the program?Lua如何在程序没有结束的情况下返回错误?
【发布时间】:2022-10-31 21:13:20
【问题描述】:

我有一个简单的 lua 代码,如下所示。

local function my_fun(x)
    return nil, error("oops", 2)
end

local res, err = my_fun("foo")
print(res)
print(err)
print("finish")

我所期望的是程序可以打印到“完成”,但我得到了程序退出。我应该怎么做才能返回错误而不是退出?

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 ?

【问题讨论】:

  • 回溯告诉您调用error 会停止执行。

标签: lua


【解决方案1】:

Lua 没有运行时错误/异常值。 error 不返回任何内容,而是触发恐慌,展开堆栈直到被捕获。

你可以抓住这样的恐慌受保护的呼叫,使用pcall()pcall 将在没有发生错误时返回一个布尔值 true 并且错误或返回值:

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"

或者,您可以定义自己的运行时错误类型。这可以像字符串一样简单,也可以像复杂的基于元表的类一样复杂。

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")

用 Lua 编程还有多个关于错误处理的章节:https://www.lua.org/pil/8.3.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 2016-02-01
    • 1970-01-01
    相关资源
    最近更新 更多