Learning

Lua + LÖVE: Make a Game · Reference

Lua quick reference

A compact syntax and standard-library reference for the Lua used throughout the course.

This sheet targets the Lua 5.1-style language used by LÖVE 11.5. Keep it open while coding; it is a memory aid, not a lesson sequence.

Values and variables

local score = 0
local title = "Orbit Runner"
local playing = true
local target = nil

print(type(score)) -- "number"

Default to local. Only false and nil are false in conditions; 0 and "" are true.

Operators

Kind Operators
arithmetic + - * / % ^
comparison == ~= < > <= >=
logic and or not
string join ..
length #value

Lua has no ++, +=, &&, or !.

score = score + 1
local label = "Score: " .. score

Conditions

if lives <= 0 then
  state = "gameover"
elseif lives == 1 then
  warning = "critical"
else
  warning = nil
end

Default with or:

local name = savedName or "Pilot"

Loops

for index = 1, 10 do
  print(index)
end

for index = 10, 1, -1 do
  print(index)
end

for index, item in ipairs(items) do
  print(index, item)
end

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

while timer > 0 do
  timer = timer - 1
end

Use ipairs for array order, pairs for unordered fields, and a backward numeric loop when removing array items.

Functions

local function add(a, b)
  return a + b
end

local sum = add(2, 3)

Multiple results:

local function position()
  return 480, 270
end

local x, y = position()

Early return:

local function update(dt)
  if paused then return end
  timer = timer - dt
end

Tables

Record/object shape:

local player = {
  x = 480,
  y = 270,
  lives = 3,
}

player.x = player.x + 10
player["lives"] = 2

Array shape—indexes start at 1:

local items = {"gold", "repair"}
table.insert(items, "shield")
local removed = table.remove(items, 2)
print(#items)

Tables are references:

local a = {score = 0}
local b = a
b.score = 5
print(a.score) -- 5

Methods and colon syntax

function player:damage(amount)
  self.lives = self.lives - amount
end

player:damage(1)
-- approximately player.damage(player, 1)

Match call style to definition style.

Modules

player.lua:

local Player = {}

function Player.new()
  return {x = 0, y = 0}
end

return Player

Another file:

local Player = require("player")
local player = Player.new()

For lib/collision.lua, use require("lib.collision").

Useful standard functions

print(value)
type(value)
tostring(value)
tonumber(text)
assert(condition, "message")

math.min(a, b)
math.max(a, b)
math.floor(number)
math.sqrt(number)
math.sin(radians)
math.cos(radians)
math.pi

string.format("Score: %03d", score)
string.format("Time: %.2f", seconds)

Frequent mistakes

Mistake Correction
if x = 3 then if x == 3 then
x += 1 x = x + 1
x != y x ~= y
if !ready if not ready
items[0] for first item items[1]
missing brace-style block close Lua blocks with end
accidental global add local

For the formal language definition, see the official Lua 5.1 reference manual.