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?
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