脚本小子_Lua错误处理

一、Lua错误处理
1、assert
  • 格式: assert(表达式,字符串),当第一个参数的执行结果为true时,则返回该表达式的值,相反为false或nil,则返回字符串的内容。
1.1、例子:接收一个整数的数字,并打印该数字;如输入的不是整数,则提示错误信息
  • 代码
print("input data:")
n = io.read()
local input = assert(tonumber(n),"invalid input: "..n.." is not a number")
print("you input data is :",input)
  • 正常运行结果

  • 错误运行结果


2、error
格式: error(表达式),显示的打印错误信息
2.1、例子: 沿用上述的例子
  • 代码
print("input data:")
n = io.read()
if not tonumber(n) then
error("invalid input")
else
print("you input data is :",n)
end
  • 错误运行结果


3、pcall
通过pcall和error可以实现类其它程序语言的try/catch的异常捕获操作
格式: pcall(function) 如果function执行成功,则返回true和对应的正确结果。如执行有误,则返回false和对应的错误信息
3.1、例子: 沿用上述的列子
  • 代码:
function foo()
n = io.read()
if not tonumber(n) then
error("invalid input")
else
return "you input data is :"..n
end
end
local status,result = pcall(foo)
print(status,result)
  • 正常运行结果

  • 错误运行结果


猜你喜欢

转载自blog.csdn.net/u014795720/article/details/80189063
今日推荐