Lua Control Flow

Lua has familiar control structures — if/else, while, for, repeat — with a few Lua-specific twists.

if/elseif/else

LUA
local score = 85

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

Lua uses then and end instead of curly braces. Only false and nil are falsy — everything else is truthy (including 0 and "").

LUA
if 0 then print("truthy!") end   -- prints! (0 is truthy in Lua)
if "" then print("truthy!") end  -- prints! (empty string is truthy)
if nil then print("never") end   -- nil is falsy

while Loop

LUA
local i = 1
while i <= 5 do
    print(i)
    i = i + 1
end

for Loop (Numeric)

LUA
-- for var = start, stop, step do
for i = 1, 10 do
    print(i)           -- 1, 2, 3, ... 10
end

for i = 10, 1, -1 do
    print(i)           -- 10, 9, 8, ... 1
end

for i = 0, 1, 0.1 do
    print(string.format("%.1f", i))  -- 0.0, 0.1, 0.2, ... 1.0
end

for Loop (Generic)

LUA
-- Numeric
for i, v in ipairs({10, 20, 30}) do
    print(i, v)
end

-- Key-value
local colors = {red = 1, green = 2, blue = 3}
for name, value in pairs(colors) do
    print(name, value)
end

repeat/until

LUA
-- Runs at least once (like do...while in C/Java)
local i = 1
repeat
    print(i)
    i = i + 1
until i > 5

break

LUA
for i = 1, 100 do
    if i > 10 then break end
    print(i)
end

Lua has no continue statement. Use goto with a label as a workaround:

LUA
for i = 1, 10 do
    if i % 2 == 0 then goto continue end
    print(i)  -- only prints odd numbers
    ::continue::
end

Tips

  • Only false and nil are falsy — 0 and "" are truthy.
  • Use ipairs for numeric iteration, pairs for key-value.
  • Lua has no ternary operator — use condition and value1 or value2.
  • Use local for all variables — global variables are accessible everywhere.

Next: functions.