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

I don't understand this?

Asked by
emite1000 335 Moderation Voter
10 years ago

I'm kind of a noob to some things in lua, and one thing I cannot seem grasp is pairs and ipairs.

Can someone, in simple terms, explain to me why for x = 1,5,2 do print(x) end prints 1, 3, and 5?

1 answer

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

For loops have a variable, in your case, x. If I do this code,

for x = 1,5 do
    print(x)
end

It will print 1 through 5. This is because each time the for loop gets to "end", it adds 1 to x. X starts off at 1, but then each time the computer sees "end", it goes back up to the top of the loop and adds 1 to x. Therefore, the first time this code runs x = 1. Then, x = 2. Then 3, and 4, and 5. Once it reaches 5, it stops.

But there's another, optional number that you can put it. By default, the loop adds 1 to x every time. But if you put in the third number, it will take that number and add it to x instead. Therefore,

for x = 1,5,2 do
    print(x) 
end

will add 2 to x every time it reaches "end".

0
Ok thank you that's what I needed. emite1000 335 — 10y
Ad

Answer this question