lua错误处理

编译

  1. loadstring在编译时不涉及词法域,也就是说,它总在全局环境中编译自己的字符串。当然,可以在字符串中用local显式的指定局部变量。
  2. loadfile加载编译lua文件,在使用lua文件中的内容前,还需要对lua文件定义,方法如下:f=loadfile("foo.lua"); f();

错误处理

  1. error抛出异常,如果error被调用,它会将参数作为返回值返回;
  2. assert第一个参数为假(表达式或函数的返回值为false或nil)时,终止程序;注意,函数默认的返回值是nil,类似void函数,所以用assert调用一个void函数(没有return)会终止程序。
  3. pcall(func[, func_arg1,...]),第一个参数是被调用函数,之后是该函数的参数。pcall的第一个返回值是pcall的返回值(false:函数抛出异常,true:函数没有抛出异常),之后是被调用函数的返回值;当被调用的函数发生异常时,不会终止程序。
  4. xpcall(func, debug_func [, func_arg1,...] ),第一个参数是被调用的函数,第二个参数是处理异常的函数(当error被调用时,调用此函数,实参由error返回值提供,也就是error的实参),之后的参数为func函数的参数。



--第8章 编译执行与错误
function loadfileTest()
    f = loadfile("5function.lua")
    print("-------------after loadfile------------")
    f() -- 定义
    print("-------------after dingyi--------------")
    main()
end

--[[ 此文件不定义main了,以免与loadfile中的main冲突
function main()
    loadfileTest()
    os.exit()
end]]

function errorTest()
    local function _foo(a)
        if not a then
             error{code=1, msg="arg is nil"}
         elseif tostring(type(a)) ~= "number" then
             error{code=2, msg="arg is not number"}
         elseif a%3==0 then
             error{code=3, msg="arg is multiple of 3"}
        end
        io.write(string.format("OK, number a is %d\n", a))
        return true, "OK"
        --return false --test assert
    end

    local res = assert(_foo(31), "test assert") --assert会终止程序
    --assert(false, "test boolean")
    --pcall中出现错误不会终止程序,第一个是pcall的返回值,之后是被调用函数的返回值
    local pcallRes, errorMsg = pcall(_foo, "3") 
    if not pcallRes then
        print(errorMsg.code, errorMsg.msg)
    end

    print("Test xpcall______________________")
    local function debug_(eTable)
        print("debug_ is called")
        print("table from error to debug_:",eTable.code, eTable.msg)
        return {code=-1, msg="xpcall return debug_'s return value"}
    end

    local xpcallRes, _fooRes1, _fooRes2 = xpcall(_foo, debug_, 6)
    if not xpcallRes then
        --若res为false,则会调用debug_错误处理函数,并且error会将自己的参数返回,作为调用debug_的实参
        print("debug_ has been called")
    else
        print("_foo results are ", _fooRes1, _fooRes2)
    end

    os.exit()
end

--loadfileTest()
errorTest()



转载于:https://my.oschina.net/acemumu/blog/358307

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值