Lua如何在程序不结束的情况下返回错误



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

local function my_fun(x)
return nil, error("oops", 2)
end
local res, err = my_fun("foo")
print(res)
print(err)
print("finish")

我所期望的是该程序可以打印到"0";完成";,但我退出了节目。我应该如何处理只返回错误而不是退出?

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 ?

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.

相关内容

最新更新