SoFunction
Updated on 2025-04-08

Explanation of the use of three loop statements in Lua

The syntax of Lua's loops and C's loops is actually similar, so it's easy to understand, so the implementation is also very simple, no different from C, and it's similar.

Examples are as follows:

-- 1、whilecycle
--[[
 Understand asCJust language,Actually, it's almost the same
 Syntax format:
 while(true)
 do
 Execution statement
 end
]]
--Define a global variablea=0
a=0
--
while(true)
do 
 a=a+1
 print("a:",a)
 if(a == 5)
 then
 break
 end
end
-- 2、forcycle
--[[
 Understand asCLanguageforJust do it,Actually, it's almost the same
 Syntax format:
 for var=exp1,exp2,exp3 do 
 The statement you want to execute
 end 
]]
--Valueforcycle
--How to understand? i = 0 , i <=5 ; i+=1 
--If the third parameter1It's a negative number,Meaning of one reduction
--parameter2As a condition,Of course, you can also pass functions,用函数作为返回值为条件实现cycle
for i = 0 , 5 , 1 do
 print("i:",i)
end
--Genericsforcycle
--similarjavaIteration of
--[[
 Format:
 for i,v in ipairs(a) 
 do 
 print(v) 
 end  
]]
--How to understand?iis the array index value,vis the array element value corresponding to the index,ipairsyesluaan iterative function,用来实现数组Iteration of
num = {1,2,3,4,5}
for i,v in ipairs(num) do
 print("num:",num[i])
end
--3、 repeat...utilcycle
--[[
 Understand asshellScripteduntilJust do it,Actually, it's almost the same,As long as the conditions are not true, it will be implemented,The conditions are established and end
 Syntax format:
 repeat
  The statement you want to execute
 until( Judgment conditions )
]]
num1 = 1
repeat 
 print("num1:",num1)
 num1 = num1 + 1 
until(num1 > 5)

Explanation run:lua  

Running results:

a:      1
a:      2
a:      3
a:      4
a:      5
i:      0
i:      1
i:      2
i:      3
i:      4
i:      5
num:    1
num:    2
num:    3
num:    4
num:    5
num1:   1
num1:   2
num1:   3
num1:   4
num1:   5

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the relevant links below