Lua 程式設計中的 Break 語句


我們希望中斷或終止迴圈的執行時使用break語句。一旦到達break語句,控制權將從當前迴圈轉移到迴圈之後編寫的任何內容。該語句中斷包含它的內部迴圈(forrepeatwhile);它不能在迴圈外部使用。中斷後,程式將立即從該中斷迴圈後面的點繼續執行。

break語句主要用於條件語句和所有型別的迴圈。它幾乎存在於所有流行的程式語言中。

語法

break

現在,我們考慮一個非常簡單的示例,我們嘗試遍歷陣列的元素,一旦我們發現數組的當前項等於我們試圖搜尋的數字,我們將中斷迴圈,然後列印陣列當前元素的值。

示例

考慮下面所示的示例 −

a = {11,12,13,14,15,16,17}
v = 16
local i = 1

while a[i] do
   if a[i] == v then break end
   i = i + 1
end

print(a[i])
print("Completed")

輸出

16
Completed

現在,我們考慮一個更復雜的情況,即當遇到重複值時,我們希望遍歷陣列的元素並中斷迴圈。

示例

考慮下面所示的示例 −

iterable = {a=1, doe1={name=1}, doe2={name=2}, doe3={name=2}}
var2 = 1
for i, v in pairs(iterable) do
   print('trying to match', i)
   if string.match(i,'doe') then
      print('match doe', i, v.name, var2)
      if v["name"] == var2 then
         txterr = "Invalid name for "..i
         duplicate = true
         print('found at i=', i)
      end
      if duplicate then
         print('breaking the loop')
         break
      end
   end
end

輸出

trying to matchdoe3
match doedoe3  2   1
trying to matchdoe2
match doedoe2  2   1
trying to matcha
trying to matchdoe1
match doedoe1  1   1
found at i=    doe1
breaking the loop

更新於: 01-12-2021

653 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.