Lua - Numeric Iterators
In Lua, there are two types of for loops −
the numeric for
the generic for
Numeric for provides a great way to iterate through an array using indexes. We can create any sequence in ascending or descending order. We can navigate an array as well using numeric for. In this article, we'll explore various use cases of numeric for based iteration using multiple examples.
Syntax
The numeric for uses the following syntax −
for var=exp1,exp2,exp3 do something end
It should be noted that we can write exp1, exp2, exp3 at the same time or we can omit one of them, and the numeric loop will not result in a compile error, though its functionality will change.
Example - Create Sequence in Ascending Order
Let's consider a simple variation of a numeric for loop, where we will try to print numbers from 1 to 10.
main.lua
Consider the example shown below −
for i = 1, 10 do print(i) end
Output
When the above code is built and executed, it produces the following result −
1 2 3 4 5 6 7 8 9 10
Okay, that was simple! How about printing the numbers in a backward order? In that case, we need the exp3 that was mentioned in the syntax of the numeric for loop.
Example - Create Sequence in Descending Order
Consider the example shown below which will print the numbers from 10 to 1.
main.lua
for i = 10, 1, -1 do print(i) end
Output
When the above code is built and executed, it produces the following result −
10 9 8 7 6 5 4 3 2 1
Now, let's explore a more common and useful case, where we want to iterate over an array in Lua, and print the values that are present inside the array.
Example - Traversing an Array of Strings
Consider the example shown below −
main.lua
names = {"John", "Joe", "Steve"}
for i = 1, 3 do
print(names[i])
end
Output
When the above code is built and executed, it produces the following result −
John Joe Steve