Lua - Generic for loop



A genetic for loop is a special repetition control structure that allows you to efficiently traverse a numerically indexed table as well as associative indexed table.

Syntax - Generic For Loop Usage with Numerically Indexed Table

The syntax of a generic for loop is as follows −

for i, v in ipairs(table)
do
   statement(s)
end

Here is the flow of control in a generic for loop −

  • For each step or precisely for each top level item in table, i is the index and v is the value associated with that index in the table.

  • We can use _ as well instead of i if i is not required.

  • We can get value using table[i] or using v.

Example - Printing Numbers if a table Using generic for Loop

In this example, we're showing the use of a generic for loop to print items in a numbers array

main.lua

numbers = { 20, 10, 30, 40, 50, 65, 12, 11}

for i, v in ipairs(numbers) do
   print(i, v)
end

Output

When the above code is built and executed, it produces the following result −

1	20
2	10
3	30
4	40
5	50
6	65
7	12
8	11

Example - Using _ in a generic for Loop

In this example, we're showing the use of a generic for loop to print items without using indexes in a numbers array

main.lua

numbers = { 20, 10, 30, 40, 50, 65, 12, 11}

for _, v in ipairs(numbers) do
   print(v)
end

Output

When the above code is built and executed, it produces the following result −

20
10
30
40
50
65
12
11

Syntax - Generic For Loop Usage with Associatively Indexed Table

The syntax of a generic for loop is as follows −

for k, v in pairs(table)
do
   statement(s)
end

Here is the flow of control in a generic for loop −

  • For each step or precisely for each top level item in table, k is the key and v is the value associated with that key in the table.

  • We can use _ as well instead of k if k is not required.

  • We can get value using v.

Example - Using Generic For on a Associative Indexed table

In this example, we're showing the use of a generic for loop to print days along with their mapped keys

main.lua

days = {
   ["Mon"]="Monday",
   ["Tue"]="Tuesday",
   ["Wed"]="Wednesday",
   ["Thu"]="Thursday",
   ["Fri"]="Friday",
   ["Sat"]="Saturday",
   ["Sun"]="Sunday"
}

for i, v in pairs(days) do
   print(i, v)
end

Output

When the above code is built and executed, it produces the following result −

Sun	Sunday
Wed	Wednesday
Sat	Saturday
Tue	Tuesday
Thu	Thursday
Fri	Friday
Mon	Monday
Advertisements