首先放一下官網的解釋:
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