Lua, lesson 5
Computers are good at doing the same thing many times. Lua has three loops: a numeric for
when you know how many times to repeat, and while and repeat when you repeat until
something happens. (There is also a generic for for walking through tables, which you will
meet in the collections lesson.)
for i = start, stop do ... end runs the body once for each value from start to stop,
including both ends. An optional third number sets the step, which can be negative to
count down:
If the range is empty (like for i = 1, 0), the body never runs.
Two details matter:
i is . It doesn't exist after .2 exercises to try what you just read.
endi = i + 1 inside the body is a
compile error. If you need to adjust it, copy it into a new local first.The start, stop and step are evaluated once, before the loop begins, so changing a variable used in them inside the body has no effect on the number of passes.
A while loop checks its condition before each pass and runs as long as it is true:
repeat checks its condition after each pass, so the body always runs at least once.
It stops when the condition becomes true (the opposite of while):
break leaves the innermost loop immediately. It's the usual way to stop on a marker value:
while true do looks like an endless loop, but the break inside gives it a way out. The
line == nil check stops the loop if the input ends before the marker.
Lua has no continue. When you want to skip the rest of one pass, wrap the remaining code in
an if, or use goto with a label, like goto continue and ::continue:: just before
end.
Read a whole number n (0 or more). Print the numbers from n down to 1, one per line, and
then Liftoff!.
Sample input:
Sample output:
Your fitness tracker sends one whole number per line: the steps walked each day. A line
containing 0 marks the end of the data, and anything after it must be ignored. Print how
many days came before the 0, and their total:
Sample input:
Sample output:
for i = 1, 3 do
print("Lap " .. i)
end
-- Lap 1
-- Lap 2
-- Lap 3for i = 0, 10, 5 do io.write(i, " ") end -- 0 5 10
print()
for i = 3, 1, -1 do io.write(i, " ") end -- 3 2 1
print()local fuel = 10
while fuel > 0 do
print("Fuel: " .. fuel)
fuel = fuel - 4
end
-- Fuel: 10, Fuel: 6, Fuel: 2local tries = 0
repeat
tries = tries + 1
until tries >= 3
print(tries) -- 3while true do
local line = io.read("l")
if line == nil or line == "end" then
break
end
print("Got: " .. line)
end33
2
1
Liftoff!Days: <count>
Total: <sum>4000
6500
3000
0Days: 3
Total: 13500