Lesson 2 of 8

Conditions & Loops

Learn if statements, while and repeat , and the two kinds of for loop. Lua marks blocks with keywords such as then, do and end instead of braces.

Lua
local grade = 87

if grade >= 90 then
  print("A")
elseif grade >= 80 then
  print("B")
else
  print("C")
end

-- Operators: == equal, ~= NOT equal (unusual!), and, or, not
if grade >= 80 and grade < 90 then
  print("solid B")
end
Lua
-- Numeric for: start, end (INCLUSIVE), optional step
for i = 1, 5 do
  print(i)             -- 1 2 3 4 5
end

for i = 10, 2, -2 do
  print(i)             -- 10 8 6 4 2
end

-- while and repeat:
local hp = 3
while hp > 0 do
  hp = hp - 1          -- no hp-- or hp -= 1 in Lua
end

repeat
  hp = hp + 1
until hp == 3          -- body runs at least once

-- break exits a loop; Lua has no 'continue'
-- (use an if, or 'goto continue' in 5.2+)
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.