Lua Cheatsheet

Control Flow

Use this Lua reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

if / elseif / else

if score >= 90 then
  grade = "A"
elseif score >= 80 then
  grade = "B"
else
  grade = "study"
end

Conditions do not need parentheses. Blocks close with end.

Boolean Operators Return Values

and and or short-circuit and return one of their operands.

local name = user.name or "Guest"
local ready = connected and authenticated

while Loop

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

repeat / until

Runs at least once because the test happens after the body.

local line
repeat
  line = io.read("l")
until line ~= ""

Numeric for

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

Syntax: for var = start, stop, step do ... end. Step defaults to 1. The loop variable is local to the loop.

Generic for

for i, value in ipairs(list) do
  print(i, value)
end

for key, value in pairs(map) do
  print(key, value)
end

Use ipairs for array-like sequences in order. Use pairs for all keys in unspecified order.

break

for i = 1, #items do
  if items[i] == target then
    found = true
    break
  end
end

break exits the innermost loop. Standard Lua has no continue keyword — see the goto continue idiom below.

goto and Labels (Lua 5.2+)

goto jumps to a ::label:: in the same function. Its main accepted use is the continue idiom:

for i = 1, 10 do
  if i % 2 == 0 then goto continue end
  print(i)
  ::continue::
end

A goto cannot jump into a block or into the scope of a local variable, so the label conventionally sits at the very end of the loop body. Supported in Lua 5.2+ and LuaJIT 2.0+ (not Lua 5.1).