Lua in Games
Lua is one of the most widely used languages in game development. Engines are written in C or C++ for speed, and Lua scripts describe the gameplay: what an enemy does, what a quest needs, what a button triggers. Designers can change behaviour and reload it without recompiling the engine.
| Engine / game | How Lua is used |
|---|---|
| LÖVE (love2d) | a complete 2D framework: your whole game is Lua |
| Roblox | Luau, a typed, sandboxed descendant of Lua 5.1 |
| Defold, Solar2D | Lua for game logic and UI |
| World of Warcraft | add-ons and the user interface |
| PICO-8 | a fantasy console programmed in a Lua subset |
| Many commercial engines | gameplay, AI, configuration, modding |
The engine APIs (love.*, Roblox services) aren't available in the playground, so engine code below is shown in non-run fences, with runnable plain-Lua versions of the underlying ideas.
The game loop in LÖVE
A LÖVE game defines callback functions that the engine calls: love.load once at start, love.update(dt) every frame with the elapsed seconds, and love.draw to render:
-- main.lua (LÖVE 11)
local player = { x = 100, y = 100, speed = 180 }
function love.load()
love.window.setTitle("Moon Walker")
end
function love.update(dt)
if love.keyboard.isDown("right") then player.x = player.x + player.speed * dt end
if love.keyboard.isDown("left") then player.x = player.x - player.speed * dt end
end
function love.draw()
love.graphics.circle("fill", player.x, player.y, 20)
love.graphics.print("x = " .. math.floor(player.x), 10, 10)
endMultiplying the speed by dt makes movement independent of the frame rate. Here is the same update logic simulated with fixed frame times:
local player = { x = 100, speed = 180 }
local keysDown = { right = true }
local function update(dt)
if keysDown.right then player.x = player.x + player.speed * dt end
if keysDown.left then player.x = player.x - player.speed * dt end
end
-- 60 frames at 60 FPS = one second of holding "right"
for _ = 1, 60 do update(1 / 60) end
print(string.format("after 1 s at 60 FPS: x = %.1f", player.x))
player.x = 100
for _ = 1, 30 do update(1 / 30) end
print(string.format("after 1 s at 30 FPS: x = %.1f", player.x))after 1 s at 60 FPS: x = 280.0
after 1 s at 30 FPS: x = 280.0
Roblox and Luau
Roblox scripts use Luau, which adds optional type annotations, compound assignment (+=) and a few built-in libraries on top of Lua 5.1. Game objects are instances in a tree, and events are connected with :Connect:
-- A Roblox Script inside a Part (Luau)
local part = script.Parent
local debounce = false
part.Touched:Connect(function(hit: BasePart)
local humanoid = hit.Parent:FindFirstChildOfClass("Humanoid")
if humanoid and not debounce then
debounce = true
humanoid.Health -= 10
task.wait(1)
debounce = false
end
end)Everything you learn in this course (tables, closures, metatables, coroutines) carries over; differences include Lua 5.1-style integer handling (all numbers are floats) and no goto.
Entities as tables
Game objects are naturally tables of data, with shared behaviour in "class" tables:
local Enemy = {}
Enemy.__index = Enemy
function Enemy.new(kind, hp, damage)
return setmetatable({ kind = kind, hp = hp, damage = damage }, Enemy)
end
function Enemy:takeHit(amount)
self.hp = math.max(self.hp - amount, 0)
return self.hp == 0
end
local wave = { Enemy.new("slime", 20, 2), Enemy.new("bat", 12, 4), Enemy.new("golem", 60, 9) }
local sword = 15
for _, e in ipairs(wave) do
local defeated = e:takeHit(sword)
print(string.format("%-6s hp %2d %s", e.kind, e.hp, defeated and "(defeated)" or ""))
endslime hp 5
bat hp 0 (defeated)
golem hp 45
Data-driven design
Lua tables make excellent data files: level layouts, item stats and dialogue trees can be written as Lua and loaded with load, with no separate parser:
local itemData = [[
return {
{ id = "potion", name = "Healing Potion", price = 25, heals = 30 },
{ id = "ether", name = "Ether", price = 60, mana = 20 },
{ id = "elixir", name = "Elixir", price = 300, heals = 999, mana = 999 },
}
]]
local items = load(itemData, "items", "t", {})() -- empty environment: data only
for _, it in ipairs(items) do
local effects = {}
if it.heals then effects[#effects + 1] = "+" .. it.heals .. " HP" end
if it.mana then effects[#effects + 1] = "+" .. it.mana .. " MP" end
print(string.format("%-15s %4dg %s", it.name, it.price, table.concat(effects, ", ")))
endHealing Potion 25g +30 HP
Ether 60g +20 MP
Elixir 300g +999 HP, +999 MP
Timers and cutscenes with coroutines
Coroutines let a cutscene or AI routine "wait" without blocking the game. A tiny scheduler resumes each routine when its timer expires:
local routines = {}
local now = 0
local function wait(seconds) coroutine.yield(seconds) end
local function start(fn)
routines[#routines + 1] = { co = coroutine.create(fn), wakeAt = 0 }
end
start(function()
print(now .. "s: door opens")
wait(2)
print(now .. "s: the knight walks in")
wait(1)
print(now .. "s: \"Who goes there?\"")
end)
for frame = 0, 4 do -- one tick per second
now = frame
for _, r in ipairs(routines) do
if coroutine.status(r.co) == "suspended" and now >= r.wakeAt then
local _, delay = coroutine.resume(r.co)
if delay then r.wakeAt = now + delay end
end
end
end0s: door opens
2s: the knight walks in
3s: "Who goes there?"
Test yourself
In LÖVE, which callback runs once per frame with the elapsed time?
love.loadlove.update(dt)love.drawlove.frame
Why multiply movement speed by dt?
- To make it faster
- So movement per second is the same at any frame rate
- Because LÖVE requires it
- To avoid integer overflow
What is Luau?
- A Lua editor
- Roblox's typed, sandboxed language derived from Lua 5.1
- A Lua package manager
- A LÖVE plugin