Lua 錯誤處理 pcall & xpcall

pcall

pcall 指的是 protected call 相似其它語言裏的 try-catch, 使用pcall 調用函數,若是函數 f 中發生了錯誤, 它並不會拋出一個錯誤,而是返回錯誤的狀態, 爲被執行函數提供一個保護模式,保證程序不會意外終止函數

語法lua

pcall( f , arg1,···)

返回值debug

  1. 函數執行狀態 (boolean)code

    • 沒有錯誤返回 trueorm

    • 有錯誤返回 falseinput

  2. 發生錯誤返回錯誤信息,不然返回函數調用返回值string

pcall 示例it

使用pcall 處理錯誤io

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

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

print ("Status: ", status)        -- 打印 "false" 
print ("Return Value: ", retval)  -- 打印 "input:2: attempt to perform arithmetic on a string value"

正常沒錯誤function

function square(a)
  return a * a
end

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

print ("Status: ", status)        -- 打印 "true"
print ("Return Value: ", retval)  -- 打印 "100"

xpcall

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

xpcall 相似 pcall xpcall接受兩個參數:調用函數、錯誤處理函數

好比使用 debug.traceback 獲取棧信息

> 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 ?
>
相關文章
相關標籤/搜索