Rob Cook


Home | GitHub | Dev.to | Donate | Contact

[6] A little bit of Lua


2026-01-09

Recall our program from the last lesson that printed the numbers from 1 to 10.

-- Debugging.

local count = 1

while count <= 10 do
  io.write(count .. " ")
  count = count + 1
end

io.write("\n")

Notice how we did three separate things with the local variable count:

This pattern of looping for a set number of iterations is so common in programming, that there is a dedicated construct for it - the for loop. Lets see what are program would look like using this loop.

-- The numeric for loop.

for count = 1, 10 do
  io.write(count .. " ")
end

io.write("\n")

Well that is much neater! We have condensed the three operations down to one expression on the for loop itself. If you debug this program, you'll see it behaves exactly the same as the while loop version - starting at 1, incrementing count each time through the loop, and stopping after 10.

What is less obvious is the variable count is scoped to the for loop. Recall scope defines where it is valid to use a variable. It only exists in for the duration of the loop. Once it ends, the variable is set to nil. Go ahead and add a final line to the program to see this in action io.write(count).

A for loop can also have a third numeric argument - the step. What do you think this program will do when run? Go ahead and type it in and see if you were correct.

-- Evens.

for count = 2, 10, 2 do
  io.write(count .. " ")
end

io.write("\n")

Armed with this information on loops have a go at the following exercises.

Exercises

  1. Write a for loop that writes out the numbers from 10 to 1. That is it counts backwards.

  2. Write a while loop that only prints out the even numbers from 2 - 10. You'll need to use the modulo operator to see if a number is even like so if count % 2 == 0 then.

Answers

  1. We can write a program like this:
-- Backwards counting.

for count = 10, 1, -1 do
  io.write(count .. " ")
end

io.write("\n")
  1. This is a bit tricker than the for loop version, but still doable.
-- Counting evens with a while loop.

local count = 1

while count <= 10 do
  if count % 2 == 0 then
    io.write(count .. " ")
  end
  count = count + 1
end

io.write("\n")
end