this image helped me understand it back then - the connection between
i
,
v
, and
x
(the table), is that
i
is the index, or position, where the loop is currently looping through in the table, and
v
is the value of that index, or position in that table. for example,
2
corresponds with
"orange"
in the table, so when the for loop’s index reaches
2
, then the
v
would be
"orange"
, and vise versa. as for the
in pairs()
, whatever goes inside the parenthesis after
pairs
is what is getting looped through. you can imagine it in an assembly form like the following.
this is just hypothetical, unreal code to demonstrate what happens behind the scenes of for loops
x (table) = {[1] = "apple", [2] = "orange", [3] = "banana"} -- this is our table
-- for loop starts, recognizes that x is a table that wants to be looped through from pairs(x)
print 1, apple -- loops through first item
print 2, orange -- loops through second item
print 3, banana -- loops through third item
-- for loop ends, code keeps running
this is what it would be in lua code (from the image)
local x = {[1] = "apple", [2] = "orange", [3] = "banana"}
for i, v in pairs(x) do
print(i, v) -- 1, apple -> 2, orange -> 3, banana
end