lua以xpcall實現try catch功能

2022-03-04 20:57:51 字數 2230 閱讀 3706

--

列印錯誤資訊

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

this function is similar topcall,except that you can set a new error handler.

xpcallcalls functionfin protected mode,usingerras the error handler.any error insidefis not propagated;instead,xpcallcatches the error,calls theerrfunction 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,xpcallalso returns all results from the call,after this first result.in case of any error,xpcallreturnsfalseplus the result fromerr.

lua以xpcall實現try catch功能

列印錯誤資訊 local function trackback errmsg local track text debug.traceback tostring errmsg 6 print trackback print track text,lua error print trackback l...

lua中xpcall實現try catch功能

local status,msg xpcall main,g trackback for ccluaengine traceback function g trackback msg local message debug.traceback msg,3 if qy.debug then self ...

lua實現繼承

lua本身沒有像c 一樣的繼承功能 但是我們可以自己實現乙個類似c 的繼承功能 書本也有詳細介紹,不過讀起來確實費解,所以本人自己寫了乙個簡單的繼承,一目了然,用來學習很容易入手 完整 基類 people function people new o o o or setmetatable o,sel...