Easy Tutorial
❮ Home Lua Break Statement ❯

Lua for Loop

Lua Loops

In the Lua programming language, the for loop statement can repeatedly execute a specified statement, with the number of repetitions controlled within the for statement.

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


Numeric for Loop

The syntax for a numeric for loop in the Lua programming language is:

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

var starts from exp1 and changes to exp2, incrementing by exp3 each time, and executes the "body" once. exp3 is optional; if not specified, it defaults to 1.

Example

for i=1,f(x) do
    print(i)
end

for i=10,1,-1 do
    print(i)
end

The three expressions in the for loop are evaluated once before the loop begins, and they are not re-evaluated later. For example, f(x) is executed only once at the start of the loop and its result is used for the subsequent iterations.

Verification is 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 of the above example is:

function
1
2
3
4
5
6
7
8
9
10

It can be seen that the function f(x) is executed only once at the start of the loop.


Generic for Loop

The generic for loop iterates over all values using an iterator function, similar to the foreach statement in Java.

The syntax for a generic for loop in the Lua programming language is:

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

i is the array index value, and v is the corresponding array element value. ipairs is an iterator function provided by Lua for iterating over arrays.

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 of the above example is:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Lua Loops

❮ Home Lua Break Statement ❯