LUA教程錯誤 32

2021-10-23 08:28:58 字數 2031 閱讀 4658

errare humanum est(拉丁諺語:犯錯是人的本性)。所以我們要盡可能的防止錯誤的發生,lua經常作為擴充套件語言嵌入在別的應用中,所以不能當錯誤發生時簡單的崩潰或者退出。相反,當錯誤發生時lua結束當前的chunk並返回到應用中。

當lua遇到不期望的情況時就會丟擲錯誤,比如:兩個非數字進行相加;呼叫乙個非函式的變數;訪問表中不存在的值等(可以通過metatables修改這種行為,後面介紹)。你也可以通過呼叫error函式顯式地丟擲錯誤,error的引數是要丟擲的錯誤資訊。

print "enter a number:"

n = io.read("*number")

if not n then error("invalid input") end

lua提供了專門的內建函式assert來完成上面類似的功能:

print "enter a number:"

n = assert(io.read("*number"), "invalid input")

assert首先檢查第乙個引數,若沒問題,assert不做任何事情;否則,assert以第二個引數作為錯誤資訊丟擲。第二個引數是可選的。注意,assert會首先處理兩個引數,然後才呼叫函式,所以下面**,無論n是否為數字,字串連線操作總會執行:

n = io.read()

assert(tonumber(n), "invalid input: " .. n .. " is not a number")

當函式遇到異常有兩個基本的動作:返回錯誤**或者丟擲錯誤。選擇哪一種方式,沒有固定的規則,不過基本的原則是:對於程式邏輯上能夠避免的異常,以丟擲錯誤的方式處理之,否則返回錯誤**。

例如sin函式,假定我們讓sin碰到錯誤時返回錯誤**,則使用sin的**可能變為:

local res = math.sin(x)

if not res then -- error

...

當然,我們也可以在呼叫sin前檢查x是否為數字:

if not tonumber(x) then     -- error: x is not a number

...

而事實上,我們既不是檢查引數也不是檢查返回結果,因為引數錯誤可能意味著我們的程式某個地方存在問題,這種情況下,處理異常最簡單最實際的方式是丟擲錯誤並且終止**的執行。

再來看乙個例子。io.open函式用於開啟檔案,如果檔案不存在,結果會如何?很多系統中,我們通過「試著去開啟檔案」來判斷檔案是否存在。所以如果io.open不能開啟檔案(由於檔案不存在或者沒有許可權),函式返回nil和錯誤資訊。依據這種方式,我們可以通過與使用者互動(比如:是否要開啟另乙個檔案)合理地處理問題:

local file, msg

repeat

print "enter a file name:"

local name = io.read()

if not name then return end -- no input

file, msg = io.open(name, "r")

if not file then print(msg) end

until file

如果你想偷懶不想處理這些情況,又想**安全的執行,可以使用assert:

file = assert(io.open(name, "r"))
lua中有乙個習慣:如果io.open失敗,assert將丟擲錯誤。

file = assert(io.open("no-file", "r"))

--> stdin:1: no-file: no such file or directory

注意:io.open返回的第二個結果(錯誤資訊)會作為assert的第二個引數。

原文:lua乙個小巧指令碼語言學習筆記

lua教程錯誤-32

Lua教程(六) 編譯執行與錯誤

1.編譯 lua中提供了dofile函式,它是一種內建的操作,用於執行lua 塊。但實際上dofile只是乙個輔助函式,loadfile才是真正的核心函式。相比於dofile,loadfile只是從指定的檔案中載入lua 塊,然後編譯這段 塊,如果有編譯錯誤,就返回nil,同時給出錯誤資訊,但是在編...

Lua 錯誤提示

1 x 10 local i 1 while i x do local x i 2 print x i i 1 end提示錯誤 stdin 1 attempt to compare nil with number 這是怎麼回事呀?它的意思是你用數字跟nil值做了比較,自然得出了錯誤。另外,你貼的 我...

Lua錯誤摘要

lua連線資料庫時報以上錯誤,下面是執行的指令碼摘錄 local cjson require cjson local mysql require resty.mysql local db mysql new db set timeout 10000 local props local res db ...