Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Explanation needed for the "for i, v in" loops?

Asked by 4 years ago

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?

0
I will remember to accept an answer that explains how the "for i, v in" loops work. AndriusTheGreat 140 — 4y

2 answers

Log in to vote
1
Answered by
oreoollie 649 Moderation Voter
4 years ago
Edited 4 years ago

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

0
So the key is the table and the value is the element inside of the table? AndriusTheGreat 140 — 4y
0
Or is the key the element of the table and the value the number it apears in? AndriusTheGreat 140 — 4y
1
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. oreoollie 649 — 4y
1
If you want me to explain this more just add me on Discord. Nitrousoxide#3667 oreoollie 649 — 4y
0
Thanks, i have used your answer several times, however, I forgot to thank you. :) AndriusTheGreat 140 — 4y
Ad
Log in to vote
1
Answered by 4 years ago
Edited 4 years ago
0
Thanks for posting an answer :) AndriusTheGreat 140 — 4y

Answer this question