Loops
The numeric for loop counts from a start to an end, optionally with a step:
for i = 1, 5 do
print(i) -- 1, 2, 3, 4, 5
end
for i = 10, 0, -5 do
print(i) -- 10, 5, 0
end
Unlike some languages, the end number is included.
while and repeat
while checks its condition before each round:
local balance = 100
local months = 0
while balance < 200 do
balance = balance * 1.1
months = months + 1
end
print(months)
repeat ... until checks after each round, so it always runs at least once:
local tries = 0
repeat
tries = tries + 1
until tries == 3
break leaves a loop early. Programs running more than 10 seconds are stopped for you here.
Your task
- Print the even numbers from 2 to 20, one per line.
- Write
sum_to(n)returning 1 + 2 + ... + n, using a loop. - Write
doublings(limit): start at 1 and double until the value reaches at leastlimit; return how many doublings it took.