Lua | 错误处理

Lua | 错误处理

1. 错误分类

1.1. 语法错误

不符合Lua语法要求的错误,只能由人工修复。

local a == 1

错误提示

lua53: error.lua:1: unexpected symbol near '=='

1.2. 运行时错误

运行时产生的错,一般像索引越界、变量不是预期的值…

function sum(a, b)
    return a + b
end

local a = 1
local b = 2

a = true

print(sum(a, b))

错误提示:

C:\Application\lua-5.3.5_Win32_bin\lua53.exe: .\error.lua:2: attempt to perform arithmetic on a boolean value (local 'a')
stack traceback:
        .\error.lua:2: in function 'sum'
        .\error.lua:11: in main chunk
        [C]: in ?

2. 错误处理函数

2.1. assert

assert(v, message)

一般用于检查变量值是否是预期

local a = 1;

assert(type(a) == "boolean", "a不是boolean类型")

错误提示:

C:\Application\lua-5.3.5_Win32_bin\lua53.exe: .\error.lua:3: a不是boolean类型
stack traceback:
        [C]: in function 'assert'
        .\error.lua:3: in main chunk
        [C]: in ?

2.2. error

error(message [, level])

level:

  • level=1(默认):为调用error位置(文件+行号)
  • level=2:指出哪个调用error的函数的函数
  • level=0:不添加错误位置信息
error("this is error message");

错误提示:

C:\Application\lua-5.3.5_Win32_bin\lua53.exe: .\error.lua:1: this is error message
stack traceback:
        [C]: in function 'error'
        .\error.lua:1: in main chunk
        [C]: in ?

2.3. pcall

检测方法执行过程中是否遇到运行时错误

function sum(a, b)
    return a + b
end

function main(a, b)
    print(sum(a, b))
end

local ok, errInfo = pcall(main, true, 2)
if ok then
    print("没有错误")
else
    print("碰到错误:" .. errInfo)
end

错误提示:

碰到错误:.\error.lua:2: attempt to perform arithmetic on a boolean value (local 'a')

2.4. xpcall

pcall可以捕获函数执行中的错误的位置,但是销毁了调栈的部份内容,有时我们需要错误方法的栈调用关系使用xpcall

function sum(a, b)
    return a + b
end

function main(a, b)
    print(sum(a, b))
end

local msgh = function(err)
    print(err)
    print(debug.traceback())
end

local status = xpcall(main, msgh, true, 2)
print(status)

错误提示:

.\error.lua:2: attempt to perform arithmetic on a boolean value (local 'a')
stack traceback:
        .\error.lua:11: in metamethod '__add'
        .\error.lua:2: in function 'sum'
        .\error.lua:6: in function 'main'
        [C]: in function 'xpcall'
        .\error.lua:14: in main chunk
        [C]: in ?
false

3. 参考

  • Lua 错误处理

你可能感兴趣的:(Lua,Lua错误处理,lua)