Alright. So what this is loop for is iterating over something (It could be items in a table, Children of a Model or workspace, It could Descendances of a screen GUI, the possibilities are endless. Let’s break the code up a bit
Index
index and value, what is this supposed to be? Well let us start off with Index first. So the Index is just the position of where the value is in the thing we are iterating over. Same shows in Python and JavaScript as well. The first item in our iteration will always take the index of 0 Take a look at this example
myTable = {"My","Name","Is","John") -- This is our table
for i,v in pairs(myTable) do
print(i) -- This prints the value of where the Index is at.
end
Our table is myTable and contains 4 different pieces of information. My, Name, Is, John. Now our first Index will be My at the Index of? If you said 0 you are correct
I could be wrong but for most programming languages the first Index of a table will ALWAYS be 0.
So if we continue our program our expected output will be
0
1
2
3
We have 4 values but since 0 always takes the first index it will print only up to 3.
Values a.k.a v
So now we know what the i is for, let’s dive into what the V is for. Always think like this
Key = i, Value = v ; Key Value Pairs
So now that we know what the value of where to access the Value which is the index, how about we learn what is the value.
Simple The value is just what the index is assign to. So My, Name, Is, John are all values of the table aka the Value. So when I said Key value pairs the I is the Key to access and the Value is just what it is assigned to and there is 2 of them making it a pair. Hence the term Key, Value pairs.
Now the parameter. As you saw I passed myTable through the parameter of pairs. Why? That is because the program has to know what we want to even iterate over. We can iterate over anything. In this case we are iterating over a table. We can iterate over Children of a table. Like this
folder = script.Parent
FolderChildren = folder:GetChildren
for i, value in pairs(FolderChildren) do
print(value.Name)
end
This will print all the names of The Children of the Folder.
When to use
Normally I’ve seen people use this if they want to iterate over something that appears a lot instead of writing a seperate variable for each seperate Child which is DRY Code.
Hopefully this helps clears up somethings on for i,v in pairs loops