• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

lua以xpcall实现try/catch功能

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

-- 打印错误信息
local function __TRACKBACK__(errmsg)
    local track_text = debug.traceback(tostring(errmsg), 6);
    print("---------------------------------------- TRACKBACK ----------------------------------------");
    print(track_text, "LUA ERROR");
    print("---------------------------------------- TRACKBACK ----------------------------------------");
    local exception_text = "LUA EXCEPTION\n" .. track_text;
    return false;
end

--[[ 尝试调一个function 这个function可以带可变参数
如果被调用的函数有异常 返回false,退出此方法继续执行其他代码并打印出异常信息;]]
function trycall(func, ...)
    local args = { ... };
    return xpcall(function() func(unpack(args)) end, __TRACKBACK__);
end
--测试代码:

trycall(function(param)
      print("message "..param)
      print("message "..nil)
        end, "test trycall")

##输出结果如下:

>lua -e "io.stdout:setvbuf 'no'" "itertor_test.lua"
message test trycall
---------------------------------------- TRACKBACK ----------------------------------------
itertor_test.lua:45: attempt to concatenate a nil value
stack traceback:
itertor_test.lua:43: in main chunk
[C]: ? LUA ERROR
---------------------------------------- TRACKBACK ----------------------------------------
>Exit code: 0

 

xpcall (f, err)

This function is similar to pcall,except that you can set a new error handler.

xpcall calls function f in protected mode,using err as the error handler.Any error inside f is not propagated;instead, xpcall catches the error,calls the err function with the original error object,and returns a status code.Its first result is the status code (a boolean),which is true if the call succeeds without errors.In this case, xpcall also returns all results from the call,after this first result.In case of any error,xpcall returns false plus the result from err.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
cocosIDE编译lua游戏程序的环境配置发布时间:2022-07-22
下一篇:
Lua 编译发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap