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

Can someone explain for loops to me?

Asked by 8 years ago

I know the basics of for loops but I see many types of for loops. For example...

for _, player in pairs - what does this mean?

for i, v in pairs -what does this mean?

for i, v in ipairs - what does this mean?

If someone could give me a good explanation that would be great!

2 answers

Log in to vote
3
Answered by 8 years ago

They are fairly simple. They are very useful as well. Pairs use tabels and run through them. Lets say you need to get everything parented to the workspace. With a for loop, it's easy. This script get's everything from the table (workspace:GetChildren() returns a table) and runs the code.

for i,v in pairs(workspace:GetChildren()) do
    print(i, v.Name)
end

--Output
> 1 Camera
   2 Baseplate
   3 Terrain

Now, let me explain further into detail.

Using for i=1,10 do, you can make a code run 10 times. Changing the 10 will run the code said number of times. Same as doing; for iterator_variable = start value, end value, increment do <-- From wiki. Ex;

for i=1,10 do
    print'Hello!'
end
--Output
> Hello!
   Hello!
   Hello!
   Hello!
   Hello!
   Hello!
   Hello!
   Hello!
   Hello!
   Hello!

When doing -,- in pairs, you can use any letter/word. Ex;

for i,v in pairs
--is the same as
for _,v in pairs
--is the same as
for index,value in pairs
--is the same as
for player,name in pairs
--I think you get the point.

If you had your own table and wanted to, let's say, loop kill them, you can do this;

local killThesePlayers={"FrstZ", "swimmaster07", "ROBLOX", "SomeRandomNoob","Player"}
for h,i in pairs(killThesePlayers) do
    if game.Players.LocalPlayer.Name==i then
        while true do
        game.Players.LocalPlayer.Character:breakJoints()    
        wait(2)
        end
    end
end

The difference between pairs and ipairs is that; pairs will run everything in the table. ipairs will run everything in the table until there's a nil value.

x={1,2,3,4,5,nil,7,8,9,10}
for _,v in pairs(x) do
    print(x)
end
--output
1
2
3
4
5
7
8
9
10

With ipairs;

x={1,2,3,4,5,nil,7,8,9,10}
for _,v in ipairs(x) do
    print(x)
end
--output
1
2
3
4
5

Well, I hope this cleared something up for you. I know I am not the best at explaining things, but I tried. :)

Ad
Log in to vote
1
Answered by 8 years ago

A loop is a chunk of code run over and over a certain amount of time until it's told not to.

for index,value(tab) in pairs do -- runs for the total #ofTheTab. The first variable being the index (the number the value is located in the tab). The second variable is the value (whatever is on that index).

These variables can be whatever you want. Personally, I use for a,b in pairs() do.

Answer this question