Lua For Loop
# Lua for Loop
[ Lua Loops](#)
In Lua programming language, the for loop statement can execute specified statements repeatedly, and the number of repetitions can be controlled in the for statement.
In Lua programming language, there are two main types of for statements:
* Numeric for loop
* Generic for loop
* * *
## Numeric for Loop
Lua programming language numeric for loop syntax format:
for var=exp1,exp2,exp3 do end
var changes from exp1 to exp2, incrementing var by exp3 as the step size each time, and executing the **"execution body"** once. exp3 is optional; if not specified, the default is 1.
### Example
## Example
for i=1,f(x)do
print(i)
end
for i=10,1,-1 do
print(i)
end
The three expressions of for are evaluated once before the loop starts, and will not be evaluated again afterwards. For example, f(x) above will only be executed once before the loop starts, and its result will be used in the subsequent loop.
Verification is as follows:
## Example
#!/usr/local/bin/lua
function f(x)
print("function")
return x*2
end
for i=1,f(5)do print(i)
end
The output result of the above example is:
function12345678910
You can see that the function f(x) is only executed once before the loop starts.
* * *
## Generic for Loop
The generic for loop traverses all values through an iterator function, similar to the foreach statement in Java.
Lua programming language generic for loop syntax format:
--Print all values of array a a = {"one", "two", "three"}for i, v in ipairs(a) doprint(i, v)end
i is the array index value, and v is the array element value corresponding to the index. ipairs is an iterator function provided by Lua, used to iterate over arrays.
### Example
Loop through array days:
## Example
#!/usr/local/bin/lua
days ={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
for i,v in ipairs(days)do print(v)end
The output result of the above example is:
SundayMondayTuesdayWednesdayThursdayFridaySaturday
[ Lua Loops](#)
YouTip