Lua嵌套循环

Lua编程语言允许在一个循环中嵌套使用另一个循环。 下面显示了几个例子来说明这个概念。

语法

Lua中嵌套for循环语句的语法如下 -

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循环内,反之亦然。

示例

以下程序使用嵌套for循环 -

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

上一篇: Lua循环 下一篇: Lua决策结构