I dont understand for i = 1, 10 loops

So, i dont understand my title. How does it work? It is a loop, i do know. i do know how to loop through tables, but not this. can somebody explain?

does i == 1 and 10? or does i == 1, 2, 3, 4, 5, 6, 7, 8, 9, 10?

17 Likes

That type of loop is called a numeric for loop.

Numeric for loops execute their body for a set amount of times.

The format of one is

for variable = start, goal, increment do

end

You start at start, going to goal by increment.

for i = 1, 10 do

end

Goes from 1 to 10 in increments of 1. If you don’t provide the increment then it defaults to 1, so adding it yourself is unnecessary.

for i = 0, 5, 0.5 do
    print(i)
end

Will print from 0 to 5, in increments of 0.5.

And the variable increases after each iteration (cycle).

43 Likes

So, i will print out 1 all the way to 10?

1 Like

Yes, gradually, in steps of 1.

The i variable goes up by 1.

1 Like

Ah, i seem to be getting it now.

So, if i did the code:

for i = 1, 10 do -- increment is default 1
    print("This message will print 10 times")
end

did i do it correctly?

7 Likes

Yes

6 Likes