"For" loop

We learnt while loop already. It executes a piece of code "while" some condition holds true. Often the loop needs to increment some variable upto some limit, like this:

x = 1
while x <= 9 do
    print(x*x)   -- x-squared
    x = x+1
end

As such special loop with "index variable" is used perhaps more often than other type of loops, special syntax was created for it by language designers, certainly very clever fellows:

for x = 1,9 do
    print(x*x)
end

Three lines instead of five! But what it means? Read it as for x taking values from 1 to 9 do something. Obviously variable x is magically incremented on every iteration.

But what if we need a "countdown", running, say, from 9 down to 1. Luckily, for syntax allows for additional, optional value of increment. Let's set it negative e.g.:

for x = 9,1,-1 do
    print(x .. ' left')
end

So we start at 9 now going to end with 1 and change the x variable by -1 on every iteration. I should confess I often forget this -1 at the end when writing such down-counting loops - what happens then? While in many languages like C/C++ loop goes from 9 to almost infinity (e.g. execution freezes), Lua prevents such misfortune - simply, no iterations are done at all! (thanks to colleague qwerty for correction here)

Now what if we want to enumerate only odd numbers? Easy - start with 1 and use increment of 2:

for x = 1,11,2 do
    print(x .. ' is odd')
end

Enough for now. Have a little practice with yourself: as an exercise try to figure out, what happens if: