Lesson 4 of 8 · 7 min

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

  1. Print the even numbers from 2 to 20, one per line.
  2. Write sum_to(n) returning 1 + 2 + ... + n, using a loop.
  3. Write doublings(limit): start at 1 and double until the value reaches at least limit; return how many doublings it took.
main.lua
-- 1. even numbers from 2 to 20


local function sum_to(n)
end

local function doublings(limit)
end

Lua 5.4 runs right here in your browser. The first run downloads about 0.4 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…