English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Lua for loop

Lua Loops

The for loop statement in Lua programming language can repeatedly execute a specified statement, and the number of repetitions can be controlled in the for statement.

There are two major types of for statements in Lua programming language:

  • Numerical for loop

  • Generic for loop

Numerical for loop

Syntax format of numerical for loop in Lua programming language:

for var=exp1,exp2,exp3 do  
    <Execution body>  
end

var from exp1 change to exp2, each change by exp3 For step increment var, and execute once "Execution body".exp3 is optional, if not specified, the default is1.

Online 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 at the beginning of the loop and will not be evaluated again. For example, the f(x) above will only be executed once at the beginning of the loop, and its result will be used in the loop below.

Verification as follows:

#!/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 as follows:

function
1
2
3
4
5
6
7
8
9
10

You can see that the function f(x) is executed only once at the beginning of the loop.

Generic for loop

The generic for loop iterates through all values by means of an iterator function, similar to the foreach statement in Java.

Syntax format of generic for loop in Lua programming language:

--Print all values of the array a  
a = {"one", "two", "three"}
for i, v in ipairs(a) do
    print(i, v)
end

i is the array index value, v is the corresponding array element value at the index. ipairs is a iterator function provided by Lua to iterate through arrays.

Online Example

Loop through the array days:

#!/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 as follows:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Lua Loops