Lua error handling pcall & xpcall

Time:2020-4-23

pcall

Pcall meansprotected callSimilar to other languagestry-catchWhen pcall is used to call a function, if an error occurs in function f, it will not throw an error, but return the status of the error, providing a protection mode for the executed function to ensure that the program will not terminate unexpectedly

grammar

pcall( f , arg1,···)

Return value

  1. Function execution status (Boolean)

    • No error returnedtrue

    • Error returnfalse

  2. If an error occurs, the error information will be returned. Otherwise, the return value of function call will be returned

Pcall example

Use pcall to handle errors

function square(a)
  return a * "a"
end

local status, retval = pcall(square,10);

Print ("status:", status) -- print "false" 
Print ("return value:", return VAL) -- print "input: 2: attempt to perform arithmetic on a string value"

No mistake

function square(a)
  return a * a
end

local status, retval = pcall(square,10);

Print ("status:", status) -- print "true"
Print ("return value:", return VAL) -- print "100"

xpcall

xpcall (f, msgh [, arg1, ···])

xpcallSimilarpcallXpcall takes two parameters: call function and error handling function

For example, use debug.traceback to get stack information

> status, err, ret = xpcall(square, debug.traceback, 10)
> status
false
> err
stdin:2: attempt to perform arithmetic on a string value
stack traceback:
    stdin:2: in function 'square'
    [C]: in function 'xpcall'
    stdin:1: in main chunk
    [C]: in ?
>