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

How do for loops work and when do you use them?

Asked by 8 years ago

I have been looking at the ROBLOX wiki and I see they used a for loop in one of the tutorials. They did not explain it that much so I still do not understand them. Also I want to know what _, and ipairs and pairs mean.

1 answer

Log in to vote
0
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
8 years ago

For loops are, obviously, loops. They will execute a block of code for each item in a list or sequence.

The most basic for loop is the numerical kind. Basically, we give it a variable, then a number to start at and a number to end at. The variable starts at the first number, then 1 is added to it every iteration until the end number is reached.

for i = 1, 5 do
    print(i)
end
--> 1 2 3 4 5

We can also put in a third number, which is the increment. Instead of 1 being added each iteration, the increment will be added each time it loops.

for i = 1, 5, 0.5 do
    print(i)
end
--> 1 1.5 2 2.5 3 3.5 4 4.5 5

We can also make it count backwards if we give it a negative increment;

for i = 5, 1, -1 do
    print(i)
end
--> 5 4 3 2 1


Pairs and ipairs are used for generic for loops. Generic for loops take advantage of iterator functions. And iterator function is a function that returns the next value (of a list) each time it is called.

Pairs and ipairs are two of these iterator functions, named such because they return pairs of values. They will give you the value in a list, as well as the position of that value in the list (the latter isn't entirely accurate, but we can think of it like that for now.) You can read about the difference here.

local list = {"val1", "val2", "val3"}

for index, value in ipairs(list) do
    print(index, value)
end
--> 1 val1 2 val2 3 val3

index and value are variables that equal what ipairs returns. They equal the current value in the list, as well as the current index, or where that value is.



_ is nothing special. It's just a variable, exactly the same as a letter. You can read about it here and here.

Ad

Answer this question