LuLua · Lesson 2 of 8

Conditions & Loops

if/then/end, while, and two flavors of for. Lua uses keywords instead of braces — code reads almost like sentences.

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
◆ Note
Only nil and false are falsy in Lua. The number 0 and the empty string "" are TRUTHY — different from Python, JavaScript, and C. 'x = x or default' is the idiomatic default-value trick.
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+)
✦ Tip
Lua arrays are 1-indexed, and numeric for is inclusive on both ends — so 'for i = 1, #list' walks a whole list. Fighting years of 0-indexed habit is the main adjustment coming from other languages.