关于xpcall函数的解释

首先放一下官网的解释:

http://www.lua.org/pil/8.5.html

通常,当一个错误发生的时候,我们想要更多的debug信息当这个错误运行的时候,至少,我们想要一个堆栈信息,展示完整的指向错误的堆栈调用。当pcall返回的时候,它销毁了一部分函数的调用过程。为了解决这个问题,lua提供了xpcall函数。当这个函数被调用的时候,错误处理函数作为第二个参数。当错误发生的时候,lua在出栈之前会调用这个error处理函数,有两个错误处理函数,debug.debug和debug.traceback函数,当error发生的时候,debug.debug给你一个lua提示。而如果调用debug.traceback的时候,建立了可以追溯函数调用错误信息。后者具有独立解释构建错误的功能。

 

 1 function myfunction(n)
 2   n = n / 11
 3 end
 4 
 5 function myerrorhandler(err) 
 6   print("ERROR:", err)
 7 end
 8 
 9 
10 status = xpcall(myfunction, myerrorhandler, 3, 4, 5)
11 print(status)

返回的结果是true

 1 function myfunction(n)
 2   n = n / nil 
 3 end
 4 
 5 function myerrorhandler(err) 
 6   print("ERROR:", err)
 7 end
 8 
 9 
10 status = xpcall(myfunction, myerrorhandler, 3, 4, 5)
11 print(status)

返回的结果是:

ERROR:    test.lua:3: attempt to perform arithmetic on a nil value
false

 

再就是关于调用非本文件的函数的时候,xpcall的参数定义也会发生相应的变化

-- test1.lua
test1 = {} function test1:Func(n) print("This is test1.lua, the n is =", n) end test1:Func(n) -- Func(2) return test1

 

-- test.lua
require
"test1" function myfunction(n) n = n / 2 print("the n is", n) end function myerrorhandler(err) print("ERROR:", err) end status = xpcall(test1.Func, myerrorhandler, test1, 4) print(status)

 

如果将xpcall函数中的test1去除,n将都会变成nul

 

posted @ 2020-06-17 15:25  Let_Life_Stop  阅读(2659)  评论(0编辑  收藏  举报