lua - (Lua)如果出现错误,有没有办法执行代码并运行函数?
问题描述
如果在执行另一个代码块时出现错误,我正在尝试执行一个函数
这就是我的意思:
在 Javascript 中,有一个名为try
and的函数catch
,您可以在其中放置代码try
并catch
在出现错误时执行
这是在行动:
try {
throw("Error")
} catch (error) {
console.log("there was an error: " + error)
}
那么我将如何在 Lua 中做到这一点?
解决方案
在 Lua 中,您需要创建一个函数,然后使用一个调用的函数pcall()
来分析函数中的任何一点是否会返回错误。这是Lua的Try-Catch
例子:
function test()
print("Hello World")
end
if not pcall(test) then -- if there is an error within the function then .....
print("ERROR")
else
print("no errors")
end
推荐阅读
- postgresql - 如何将相关组保持在一起?
- ios - 更改选项卡控制器选项卡时的运行方法(iOS)
- .htaccess - htaccess 中的 ^([^.?]+)$ 和 ^(\w+)$ 重写规则说明
- c++ - 模拟概念和约束的推荐方法是什么?
- r - 在 R 中的面板线性模型(回归)中添加虚拟变量
- python - 使用连续隐马尔可夫模型的时间序列预测步骤
- django - 将自己分组的排名系统使用什么数据结构?
- javascript - 选择器是比类方法更好的获取计算数据的方法吗?
- javascript - 如何从 XHR 请求响应字符串转换/解码 base64
- javascript - json字符串化重复键