I don't quite understand for loops, even though I've read about it on the wiki and watched tutorials, could someone give me an example of for loops?
For Loops are essentially loops that run for a specific period. There are two types of for loops.
1 Numeric for loops
and generic for loops
both have adept value.
Numeric For Loops has a starting, middle and an ending position, e.g
.
The first value of a Numeric For Loop
has to be less than the first one unless it wouldn't work.
for i = 1,10 do print (i) end
OUTPUT: 1 2 3 4 5 6 7 8 9 10
On the other hand, Generic For Loops are useful for looping through objects in the Workspace.
EX: You can loop through the character and get all the descendants (children) of the character's body parts, 1by1.
for i,v in pairs (game.Players:GetPlayers()) do print (v) end
Possible Outcome:
It should print every single player in the Workspace.
Here's a video about For Loops.
Refined by JesseSong, fixed grammatical errors. Date: February 20, 2021.
Hello there!
There are two types of for loops. An in pairs
loop, and an i = 0, 1 do
loop.
i = 0, 1 loops:
The i = 0, 1 do
will count down between a certain point.
For example:
for i = 0, 10 do wait(1) print(i) end
The output would say: "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"
That loop will wait 1 second and print "i", which is the current number it's at.
In pairs loop:
The in pairs loop
loops through a table until there are no more values left to loop through.
For example:
local myFruitTable = { "Apples", "Bananas", "Grapes" } for i, v in pairs(myFruitTable) do print(v) print(i) end
The output would say: "Apples" "1" "Bananas" "2" "Grapes" "3".
"V" stands for value, and "I" stands for index. For example, "Apples" has an index of 1, "Bananas" has an index 2, etc. It's basically the order number. "V" is the value. For example, print(v)
would print out "Apples", "Bananas", and so on and so forth.
The in pairs
loop is also useful using the Instance:GetChildren()
function. That function returns a table, which means you could use the in pairs
loop on it. For example:
local children = workspace:GetChildren() for i, v in pairs(children) do v:Destroy() end
That would destroy the children of workspace. You could've also used the Instance:ClearAllChildren()
function.
Please accept and upvote my answer if it helped.
A for loop can be used for counting between integers. EG:
for count = 1, 5 do print(count) end
Essentially, it checks each 'point' between two given values.