Lua編程中使用嵌套迴圈的使用教程_Lua

來源:互聯網
上載者:User

 Lua程式設計語言允許使用一個迴圈內嵌另一個迴圈。下文將介紹幾個例子來說明這一概念。
文法

在Lua中嵌套迴圈文法語句如下:

複製代碼 代碼如下:
for init,max/min value, increment
do
   for init,max/min value, increment
   do
      statement(s)
   end
   statement(s)
end

在Lua程式設計語言中的嵌套的while迴圈的文法語句,如下所示:

複製代碼 代碼如下:
while(condition)
do
   while(condition)
   do
      statement(s)
   end
   statement(s)
end

Lua程式設計語言嵌套repeat...until迴圈的文法語句如下:

複製代碼 代碼如下:
repeat
   statement(s)
   repeat
      statement(s)
   until( condition )
until( condition )

在迴圈嵌套最後需要說明的是,可以把任何類型的迴圈放入到任何其他類型的迴圈裡面。例如,一個for迴圈可以在另外一個while迴圈內,反之亦然。
例如:

下面的程式使用一個嵌套的迴圈:

複製代碼 代碼如下:
j =2
for i=2,10 do
   for j=2,(i/j) , 2 do
      if(not(i%j))
      then
         break
      end
      if(j > (i/j))then
         print("Value of i is",i)
      end
   end
end

  

當建立和運行上面的代碼,它會產生以下結果。

複製代碼 代碼如下:
Value of i is 8
Value of i is 9
Value of i is 10

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.