typestar

Loops in Lua

Numeric for counts; while guards; repeat tests at the end.

-- The numeric for counts start, stop, optional step.
for floor = 1, 3 do
  print("Descending to floor " .. floor)
end

for count = 10, 4, -2 do
  print("Rope remaining: " .. count .. " ft")
end

-- while and repeat guard on a condition; repeat tests at the end.
local stamina = 9
while stamina > 6 do
  stamina = stamina - 1
end
repeat
  stamina = stamina + 2
until stamina >= 10
print("Rested back to " .. stamina)

How it works

  1. for floor = 1, 3 do counts inclusively.
  2. A third clause steps: 10, 4, -2 walks down by twos.
  3. repeat ... until always runs its body at least once.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
408
Tokens
74
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 63 seconds.

Type this snippet

Step 2 of 3 in Control flow, step 5 of 27 in Language basics.

← Previous Next →

Loops in other languages