Lua中assert( )函数的使用


当Lua遇到不期望的情况时就会抛出错误,比如:两个非数字进行相加;调用一个非函数的变量;访问表中不存在的值等。你也可以通过调用error函数显示的抛出错误,error的参数是要抛出的错误信息。
assert(a,b) a是要检查是否有错误的一个参数,b是a错误时抛出的信息。第二个参数b是可选的。
  • 1
  • 2
  • 3
print("enter a number:") n = io.read("*number") if not n then error("invalid input") end
  • 1
  • 2
  • 3
  • 4
  • 5

Lua提供了专门的内置函数assert( )来完成上述的类似功能

print("enter a number:") n = assert(io.read("*number"), "invalid input")
  • 1
  • 2

assert首先检查的是第一个参数是否返回错误,如果不返回错误,则assert简单返回,否则则以第二个参数抛出异常信息。 
assert()是普通函数,他首先计算两个参数,然后在调用函数,如:

n = io.read() assert(tonumber(n), "invalid input:" .. n .. "is not a number")
  • 1
  • 2

先进行tonumber(n), "invalid input:" .. n .. "is not a number"这两个参数的计算。

没用assert( )时:

input = io.read("*number") print(input)
  • 1
  • 2

运行结果:

nil [Finished in 0.3s]
  • 1
  • 2

用assert( )时:

input = assert(io.read("*number")) print(input)
  • 1
  • 2

运行结果:

lua: D:\UserProfiles\BenLuo\Desktop\study\test.lua:44: assertion failed! stack traceback: [C]: in function 'assert' D:\UserProfiles\BenLuo\Desktop\study\test.lua:44: in main chunk [C]: ? [Finished in 0.3s with exit code 1]


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM