一、Lua錯誤處理
1、assert
- 格式: assert(表達式,字符串),當第一個參數的執行結果爲true時,則返回該表達式的值,相反爲false或nil,則返回字符串的內容。
1.1、例子:接收一個整數的數字,並打印該數字;如輸入的不是整數,則提示錯誤信息
print("input data:")
n = io.read()
local input = assert(tonumber(n),"invalid input: "..n.." is not a number")
print("you input data is :",input)
2、error
格式: error(表達式),顯示的打印錯誤信息
2.1、例子: 沿用上述的例子
print("input data:")
n = io.read()
if not tonumber(n) then
error("invalid input")
else
print("you input data is :",n)
end
3、pcall
通過pcall和error可以實現類其它程序語言的try/catch的異常捕獲操作
格式: pcall(function) 如果function執行成功,則返回true和對應的正確結果。如執行有誤,則返回false和對應的錯誤信息
3.1、例子: 沿用上述的列子
function foo()
n = io.read()
if not tonumber(n) then
error("invalid input")
else
return "you input data is :"..n
end
end
local status,result = pcall(foo)
print(status,result)