Control Structures

7.1 if / elseif / else

local score = 85
if score >= 90 then
    print("A")
elseif score >= 80 then      -- elseif is one word
    print("B")
else
    print("C")
end

7.2 Loops

-- Numeric for: start, stop (inclusive), optional step
for i = 1, 5 do print(i) end
for i = 10, 1, -2 do print(i) end           --> 10 8 6 4 2
for i = 0, 1, 0.25 do print(i) end          -- float steps work
-- The loop variable is local to the loop. Don't modify it inside the loop (5.4: it's a copy).

-- Generic for (with iterators)
local fruits = {"apple", "banana", "cherry"}
for index, value in ipairs(fruits) do print(index, value) end
local ages = {ana = 30, bo = 25}
for key, value in pairs(ages) do print(key, value) end   -- order is unspecified

-- while
local n = 3
while n > 0 do
    print(n)
    n = n - 1
end

-- repeat-until (body runs at least once; locals are visible in the condition)
repeat
    local line = io.read()
until line == nil or line == "quit"

7.3 break, goto and continue

goto can't jump into a block or into the scope of a local. Use it sparingly (mostly for continue and nested breaks).

for i = 1, 10 do
    if i > 5 then break end
end

-- Lua has no `continue`; use goto (5.2+)
for i = 1, 10 do
    if i % 2 == 0 then goto continue end
    print(i)
    ::continue::
end

-- Breaking out of nested loops
for i = 1, 3 do
    for j = 1, 3 do
        if i * j == 4 then goto done end
    end
end
::done::