首页 > 解决方案 > (Lua)如果出现错误,有没有办法执行代码并运行函数?

问题描述

如果在执行另一个代码块时出现错误,我正在尝试执行一个函数

这就是我的意思:

在 Javascript 中,有一个名为tryand的函数catch,您可以在其中放置代码trycatch在出现错误时执行

这是在行动:

try {
  throw("Error")
} catch (error) {
  console.log("there was an error: " + error)
}

那么我将如何在 Lua 中做到这一点?

标签: 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

推荐阅读