I have recently read the Roblox Developer page about the for loop, the article is well-written however I feel that they have gone a bit too fast over the "for i, v in" loops. Therefore my question is: how does the "for i, v in" loops work?
Explanation needed for the "for i, v in" loops?
2 answers
This is called a Generic For Loop (GFL). A GFL uses an iterator function such as ipairs or next. An iterator function simply returns the next element in a table every time it's called. These functions usually return two values, typically named i and v. The first one represents the key of the entry and the second represents the value of the entry. So every time the loop is run the variables i and v are declared with their corresponding values, allowing you to manipulate the table. Here's an example to help you out:
for i, v in ipairs(workspace:GetChildren()) do -- This iterator function will sequentially iterate through the children of Workspace
print(v.Name) -- Since`v contain the object in the workspace, we can check a property of it.
end
Here's a good page for reference: https://www.lua.org/pil/4.3.5.html
5 comments
So the key is the table and the value is the element inside of the table?
Or is the key the element of the table and the value the number it apears in?
Sorry it took so long to respond. A key is an index for the value. It's like if I made a numbered grocery list and the first thing was "milk" the key would be 1 and the value would be "Milk." In Lua the key can be any datatype, for example a string.
If you want me to explain this more just add me on Discord. Nitrousoxide#3667
Thanks, i have used your answer several times, however, I forgot to thank you. :)
1 comment
Thanks for posting an answer :)
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
I will remember to accept an answer that explains how the "for i, v in" loops work.