Loops

<< Conditions | Lua | Metatables >>

Loops are operations that are repeated endlessly until you stop or break the loop.

There are a few different ways how to use loops in lua and I will show you only two of them - I consider this as enough for the first time.

Loops example 1

for i=1,4 do print(i) end

Output

 1
 2 
 3
 4

Example 2

 for i=1,2,0.5 do print(i) end

Output

 1
 1.5
 2

Example 3

 i=1 
while (i<4) do i = i + 1 end 

Output

 1
 2
 3
The example show different loops. But there are more ways using loops. The for statement in lua is quite useful as you can customize it yourself. If you want to iterate about the elements of a table, you could do this in this way:

Example

 tab = { "a","b","c", somewhere="else" }
for key,value in ipairs(tab) do
  print(key,"->",value)
end 

Output

 1 → a
 2 → b
 3 → c
The "somewhere" key will not be iterated: ipairs iterates only over the values in a table that are numerated beginning from 1 on until the next number is now longer available. If you want to iterate over all elements of a table (but it is slower) you could write it this way:

Example

 for key,value in pairs(tab) do 
  print(key,"->",value)
end
This will print all keys and values of the table.