我有一个 lua 函数,它接受多个参数并返回与参数一样多的值。每个返回值对应一个参数。为了说明这一点,请考虑一个从数据库中读取键/值对值的函数:
val1, val2, val3 = my_function("key1", "key2", "key3");
val1 = my_function("key1");
从
my_function
返回错误的最佳方法是什么? ? (例如,如果提供的“ key ”无效)我知道一种方法是在错误时返回两个值,
nil
和一个错误字符串。这是最好的方法吗?例如:val1, val2, val3 = my_function("key1", "key2", "key3");
if val1 then
-- Use val1, val2, and val3.
else
print("ERROR: " .. val2);
end
编辑
补充几点:
lua_pcall()
从 C 程序中执行。 . my_function()
在 C 中实现。my_function()
失败,它还应该返回一个错误代码(或消息),指示失败的原因。 最佳答案
在 Lua 中抛出错误的标准方法是通过错误函数( manual , api )或通过 assert (内部使用 error
反正)。
由于您的函数是用 C 编写的,您应该调用 lua_error在里面,获得同样的效果。
但请记住,您的函数现在是“不安全的”。如果未修改,则以下代码将执行等效于“抛出异常”的操作,从而在 key1、key2 或 key3 为“错误”时停止程序:
val1, val2, val3 = my_function("key1", "key2", "key3")
有时,如果输入错误,让程序“崩溃”是可以的。根据您的设置,用户将收到一条消息,其中包含最后一个错误、堆栈跟踪或类似内容。
如果“让程序崩溃”不是一个选项,您可以使用 pcall 用“try-catch”块包围它。函数,并添加一个名为
ok
的新变量:ok, val1, val2, val3 = pcall(my_function, "key1", "key2", "key3")
if ok then
-- Use val1, val2, and val3.
else
print("ERROR: " .. val1) -- notice that we use val1 here, not val2
end
请注意,您不必输入
pcall
正好在 my_function
之上.与异常一样,错误恢复可能发生在调用链的更高位置:在函数调用中 my_function
,或者调用那个函数的函数,等等。例如,如果你调用 my_function
来自一个名为 parent
的函数,以及来自一个叫 grandParent
的 parent , 你可以这样做:-- parent is "insecure" since my_function is "unprotected"
function parent(key1, key2)
local val1, val2, val3 = my_function(key1, key2, "key3")
return val1, val2, val3
end
-- grandParent calls parent in a "safe" way
function grandParent()
local ok, val1, val2, val3 = pcall(parent, "key1", "key2")
if ok then
-- Use val1, val2, and val3.
else
print("ERROR: " .. val1)
end
end
关于lua - 从返回多个值的 lua 函数返回错误的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8752855/