zoukankan      html  css  js  c++  java
  • 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:UserProfilesBenLuoDesktopstudy	est.lua:44: assertion failed!
    stack traceback:
        [C]: in function 'assert'
        D:UserProfilesBenLuoDesktopstudy	est.lua:44: in main chunk
        [C]: ?
    [Finished in 0.3s with exit code 1]
  • 相关阅读:
    Valid Palindrome
    Construct Binary Tree from Inorder and Postorder Traversal
    LeetCode: LRU Cache
    LeetCode: Max Points on a Line
    LeetCode: Evaluate Reverse Polish Notation
    LeetCode:Two Sum
    LeetCode: Binary Tree Postorder Traversal
    LeetCode:Binary Tree Maximum Path Sum
    iOS开发 入门学习总结(二)Objective-C 语法特性总结
    LeetCode: Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/-colin/p/8275920.html
Copyright © 2011-2022 走看看