The generic for in Lua allows us to iterate over the values in an iterator fashion; it is much more powerful even though it looks simple. The Lua library has plenty of iterators, over which we can use the generic for loop.
for i, v in pairs(x) do ... ... end
The i in the above syntax denotes the index of the items we are going to iterate over only by one, and the v denotes the actual values of those items. The x is the iterable item over which we are iterating, it can be a list, array, or map.
Now let’s consider a simple example where we will try to iterate over the items of an array and will print the index of the items in the array.
Consider the example shown below −
a = {11,12,13,14,15,16,17} for i, v in pairs(a) do print(i) end
1 2 3 4 5 6 7
Now, instead of printing the index, let’s print both the indexes and values that are present inside the array.
Consider the example shown below −
a = {11,12,13,14,15,16,17} for i, v in pairs(a) do print(i) print(v) end
1 11 2 12 3 13 4 14 5 15 6 16 7 17
It should be noted that we can also omit the variable i or v depending on our use-case. Consider a case where we just need to print the value of the array. In that case, we can remove the identifier for index from the generic for loop.
Consider the example shown below −
a = {11,12,13,14,15,16,17} for _, v in pairs(a) do print(v) end
11 12 13 14 15 16 17