Lua's pcall and xpcall

If you need to handle errors in Lua, you must use the function pcall (protected call) to wrap the code that needs to be executed,

pcall receives a function and passes the latter parameters, and executes it. The execution result: error or no error; return value true or false, errorinfo

Here 33 is the parameter passed to the specified function.

Such as the following code:

if pcall(function(i) print("i am "..i) end, 33) then
    print("true")
else
    print("false")
end

--If you want to pass multiple parameters

<pre name="code" class="plain">if pcall(function(i,j) print("i am "..i..j) end, 33,44) then
    print("true")
else
    print("false")
end

 
The result of execution is:
i am 33
true
or
i am 3344
true
Lua provides the xpcall function, xpcall receives the second parameter-an error handling function, when an error occurs, Lua will call it before calling unwind Error handling function, so you can use the debug library in this function to get additional information about the error.

The debug library provides two general error handling functions:

debug.debug: Provides a Lua prompt to allow users to come up with the reason for the error.
debug.traceback: build an extended error message based on the call to 桟

xpcall(function(i) print(i) error('error..') end, function()  print(debug.traceback()) end, 33)
输出结果:
stack traceback:
    test.lua:1: in function <test.lua:1>
    [C]: in function 'error'
    test.lua:1: in function <test.lua:1>
    [C]: in function 'xpcall'
    test.lua:1: in main chunk
    [C]: ?

Guess you like

Origin blog.csdn.net/Momo_Da/article/details/106612511