Lua編程語言允許使用一個循環(huán)內(nèi)嵌另一個循環(huán)。下文將介紹幾個例子來說明這一概念。
在Lua中嵌套循環(huán)語法語句如下:
for init,max/min value, increment do for init,max/min value, increment do statement(s) end statement(s) end
在Lua編程語言中的嵌套的while循環(huán)的語法語句,如下所示:
while(condition) do while(condition) do statement(s) end statement(s) end
Lua編程語言嵌套repeat...until循環(huán)的語法語句如下:
repeat statement(s) repeat statement(s) until( condition ) until( condition )
在循環(huán)嵌套最后需要說明的是,可以把任何類型的循環(huán)放入到任何其他類型的循環(huán)里面。例如,一個for循環(huán)可以在另外一個while循環(huán)內(nèi),反之亦然。
下面的程序使用一個嵌套的循環(huán):
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
當建立和運行上面的代碼,它會產(chǎn)生以下結(jié)果。
Value of i is 8 Value of i is 9 Value of i is 10