TExcelTAD
Home › Lua › Lua Mini Project

Lua Mini Project

In this project you'll build a small text adventure engine, the kind of game logic Lua is often used for. It brings together most of the course: tables as data, a class with metatables, string patterns for parsing commands, a dispatch table of functions, closures, coroutines for a scripted event, and saving the game as Lua source with %q.

By the end the game understands commands like these:

text
look
go north
take lamp
inventory
use lamp
save

Every step is a complete program that you can run and change. The playground can't wait for keyboard input, so the "player" is a list of command strings; in a terminal game you would read them with io.read("l") in a loop.

Step 1: The world as data

Rooms are tables: a description, exits (direction → room id) and items. Keeping the world as data separate from code means designers can add rooms without touching the engine.

lua · try it yourself
local rooms = {
  hall = {
    name = "Great Hall",
    text = "Dusty banners hang from the walls.",
    exits = { north = "library", east = "kitchen" },
    items = { "key" },
  },
  library = {
    name = "Library",
    text = "Shelves of crumbling books. It is very dark.",
    exits = { south = "hall" },
    items = { "lamp" },
  },
  kitchen = {
    name = "Kitchen",
    text = "A cold hearth and a locked trapdoor.",
    exits = { west = "hall" },
    items = {},
  },
}

local function sortedKeys(t)
  local keys = {}
  for k in pairs(t) do keys[#keys + 1] = k end
  table.sort(keys)
  return keys
end

local function describe(id)
  local room = rooms[id]
  local lines = { "== " .. room.name .. " ==", room.text }
  if #room.items > 0 then
    lines[#lines + 1] = "You see: " .. table.concat(room.items, ", ")
  end
  lines[#lines + 1] = "Exits: " .. table.concat(sortedKeys(room.exits), ", ")
  return table.concat(lines, "\n")
end

print(describe("hall"))
print()
print(describe("library"))
== Great Hall ==
Dusty banners hang from the walls.
You see: key
Exits: east, north

== Library ==
Shelves of crumbling books. It is very dark.
You see: lamp
Exits: south

sortedKeys makes the exit list deterministic: pairs alone could list north and east in either order.

Step 2: A Player class

The player has a location and an inventory. Methods use : so they receive self. The inventory is a set (item → true) for instant lookups.

lua · try it yourself
local Player = {}
Player.__index = Player

function Player.new(start)
  return setmetatable({ room = start, inventory = {}, moves = 0 }, Player)
end

function Player:has(item) return self.inventory[item] == true end

function Player:take(item, room)
  for i, it in ipairs(room.items) do
    if it == item then
      table.remove(room.items, i)
      self.inventory[item] = true
      return true
    end
  end
  return false
end

function Player:itemList()
  local list = {}
  for item in pairs(self.inventory) do list[#list + 1] = item end
  table.sort(list)
  return list
end

local hall = { items = { "key", "map" } }
local p = Player.new("hall")
print(p:take("map", hall), p:take("sword", hall))
print(p:has("map"), p:has("key"))
print("carrying: " .. table.concat(p:itemList(), ", "))
print("left in hall: " .. table.concat(hall.items, ", "))
true	false
true	false
carrying: map
left in hall: key

Step 3: Parsing commands

A command is a verb, optionally followed by an object. A pattern splits it, and aliases map short forms (n, get, i) to the canonical verbs:

lua · try it yourself
local aliases = {
  n = "go north", s = "go south", e = "go east", w = "go west",
  get = "take", i = "inventory", l = "look",
}

local function parse(line)
  line = line:lower():match("^%s*(.-)%s*
quot;) -- trim and lower-case local verb, rest = line:match("^(%S+)%s*(.*)
quot;) if not verb then return nil end local expanded = aliases[verb] if expanded then local v2, obj = expanded:match("^(%S+)%s*(.*)
quot;) verb, rest = v2, (obj ~= "" and obj) or rest end return verb, rest ~= "" and rest or nil end for _, line in ipairs({ "look", " Go North ", "n", "get lamp", "i", "", "dance wildly" }) do local verb, obj = parse(line) print(string.format("%-14s -> %s | %s", ("%q"):format(line), tostring(verb), tostring(obj))) end
"look"         -> look | nil
"  Go North "  -> go | north
"n"            -> go | north
"get lamp"     -> take | lamp
"i"            -> inventory | nil
""             -> nil | nil
"dance wildly" -> dance | wildly

%q puts quotes around each input so you can see the spaces. It can't take a width itself (%-14q is an error), so the quoted text is padded with a separate %-14s.

Step 4: A dispatch table of commands

Each verb maps to a function. Adding a command means adding one entry; there is no long if/elseif chain. Unknown verbs get a friendly message:

lua · try it yourself
local rooms = {
  hall = { name = "Great Hall", exits = { north = "library" }, items = { "key" } },
  library = { name = "Library", exits = { south = "hall" }, items = { "lamp" } },
}
local player = { room = "hall", inventory = {} }

local commands = {}

function commands.look()
  local room = rooms[player.room]
  local items = #room.items > 0 and (" Items: " .. table.concat(room.items, ", ")) or ""
  return "You are in the " .. room.name .. "." .. items
end

function commands.go(dir)
  if not dir then return "Go where?" end
  local target = rooms[player.room].exits[dir]
  if not target then return "You can't go " .. dir .. "." end
  player.room = target
  return commands.look()
end

function commands.take(item)
  local items = rooms[player.room].items
  for i, it in ipairs(items) do
    if it == item then
      table.remove(items, i)
      player.inventory[#player.inventory + 1] = item
      return "Taken: " .. item
    end
  end
  return "There is no " .. tostring(item) .. " here."
end

local function run(verb, obj)
  local handler = commands[verb]
  if not handler then return "I don't know how to '" .. verb .. "'." end
  return handler(obj)
end

print(run("look"))
print(run("take", "key"))
print(run("go", "west"))
print(run("go", "north"))
print(run("take", "sword"))
print(run("sing"))
You are in the Great Hall. Items: key
Taken: key
You can't go west.
You are in the Library. Items: lamp
There is no sword here.
I don't know how to 'sing'.

Step 5: A scripted event with a coroutine

When the player first lights the lamp in the library, a short story plays out over the next few turns. A coroutine makes the script read top to bottom; the engine resumes it once per turn:

lua · try it yourself
local events = {}

local function startEvent(fn)
  events[#events + 1] = coroutine.create(fn)
end

local function tickEvents(log)
  for _, ev in ipairs(events) do
    if coroutine.status(ev) == "suspended" then
      local ok, msg = coroutine.resume(ev)
      if ok and msg then log(msg) end
    end
  end
end

startEvent(function()
  coroutine.yield("The lamp flickers to life.")
  coroutine.yield("A draught blows from behind a bookshelf...")
  coroutine.yield("The bookshelf swings open: a secret passage!")
end)

for turn = 1, 4 do
  tickEvents(function(msg) print("turn " .. turn .. ": " .. msg) end)
end
print("events finished:", coroutine.status(events[1]))
turn 1: The lamp flickers to life.
turn 2: A draught blows from behind a bookshelf...
turn 3: The bookshelf swings open: a secret passage!
events finished:	dead

On turn 4 the coroutine returns without yielding a message, so nothing is printed and it becomes dead.

Step 6: Saving and loading

A saved game can simply be Lua source code that returns a table. %q quotes strings safely, keys are sorted for a stable file, and loading uses load with an empty environment, so a tampered save file can't call any functions:

lua · try it yourself
local function serialize(value, indent)
  indent = indent or ""
  local t = type(value)
  if t == "string" or t == "number" or t == "boolean" then
    return string.format("%q", value)
  elseif t == "table" then
    local keys = {}
    for k in pairs(value) do keys[#keys + 1] = k end
    table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
    local parts = {}
    for _, k in ipairs(keys) do
      parts[#parts + 1] = string.format("%s  [%s] = %s,", indent,
        string.format("%q", k), serialize(value[k], indent .. "  "))
    end
    return "{\n" .. table.concat(parts, "\n") .. "\n" .. indent .. "}"
  end
  error("cannot save a " .. t)
end

local state = { room = "library", moves = 7, inventory = { "key", "lamp" }, lampLit = true }
local saved = "return " .. serialize(state)
print(saved)

local restored = load(saved, "savegame", "t", {})()
print(restored.room, restored.moves, restored.inventory[2], restored.lampLit)
return {
  ["inventory"] = {
    [1] = "key",
    [2] = "lamp",
  },
  ["lampLit"] = true,
  ["moves"] = 7,
  ["room"] = "library",
}
library	7	lamp	true

Step 7: The complete game

Now everything comes together: the world data, the Game class holding the state, the parser, the command table, the lamp event, a win condition and a save. The script at the bottom plays a full session.

lua · try it yourself
-- World -----------------------------------------------------------------
local function newWorld()
  return {
    hall = { name = "Great Hall", text = "Dusty banners hang from the walls.",
             exits = { north = "library", east = "kitchen" }, items = { "lamp" } },
    library = { name = "Library", text = "Shelves of crumbling books.",
                exits = { south = "hall" }, items = { "key" }, dark = true },
    kitchen = { name = "Kitchen", text = "A cold hearth and a locked trapdoor.",
                exits = { west = "hall" }, items = {} },
    cellar = { name = "Cellar", text = "Barrels of ancient wine. You found the treasure!",
               exits = { up = "kitchen" }, items = { "gold" } },
  }
end

local function sortedKeys(t)
  local keys = {}
  for k in pairs(t) do keys[#keys + 1] = k end
  table.sort(keys)
  return keys
end

-- Game class ------------------------------------------------------------
local Game = {}
Game.__index = Game

function Game.new()
  local g = setmetatable({ rooms = newWorld(), room = "hall", inventory = {},
                           moves = 0, events = {}, over = false }, Game)
  return g
end

function Game:say(msg) print("  " .. msg) end

function Game:has(item)
  for _, it in ipairs(self.inventory) do if it == item then return true end end
  return false
end

function Game:look()
  local r = self.rooms[self.room]
  if r.dark and not self.lampLit then
    return self:say("It is pitch black. You might trip over something.")
  end
  self:say(r.name .. ": " .. r.text)
  if #r.items > 0 then self:say("You see: " .. table.concat(r.items, ", ")) end
  self:say("Exits: " .. table.concat(sortedKeys(r.exits), ", "))
end

-- Commands ------------------------------------------------------------
local commands = {}

function commands.look(g) g:look() end

function commands.go(g, dir)
  local target = dir and g.rooms[g.room].exits[dir]
  if not target then return g:say("You can't go that way.") end
  g.room = target
  g:look()
  if target == "cellar" then g.over = true end
end

function commands.take(g, item)
  local r = g.rooms[g.room]
  if r.dark and not g.lampLit then return g:say("You fumble in the dark.") end
  for i, it in ipairs(r.items) do
    if it == item then
      table.remove(r.items, i)
      g.inventory[#g.inventory + 1] = item
      return g:say("Taken: " .. item)
    end
  end
  g:say("There is no " .. tostring(item) .. " here.")
end

function commands.inventory(g)
  local items = { table.unpack(g.inventory) }
  table.sort(items)
  g:say(#items > 0 and ("You carry: " .. table.concat(items, ", ")) or "You carry nothing.")
end

function commands.use(g, item)
  if not g:has(item) then return g:say("You don't have that.") end
  if item == "lamp" and not g.lampLit then
    g.lampLit = true
    g:say("You light the lamp.")
    g.events[#g.events + 1] = coroutine.create(function()
      coroutine.yield("The shadows retreat. Something glints in the corner.")
    end)
  elseif item == "key" and g.room == "kitchen" then
    g.rooms.kitchen.exits.down = "cellar"
    g:say("The trapdoor creaks open. Stairs lead down.")
  else
    g:say("Nothing happens.")
  end
end

local aliases = { n = "go north", s = "go south", e = "go east", w = "go west",
                  d = "go down", get = "take", i = "inventory", l = "look" }

local function parse(line)
  line = line:lower():match("^%s*(.-)%s*
quot;) line = aliases[line] or line local verb, rest = line:match("^(%S+)%s*(.*)
quot;) if verb and aliases[verb] then verb = aliases[verb] end return verb, rest ~= "" and rest or nil end function Game:command(line) print("> " .. line) local verb, obj = parse(line) local handler = verb and commands[verb] if not handler then self:say("I don't understand that.") else self.moves = self.moves + 1 handler(self, obj) end for _, ev in ipairs(self.events) do if coroutine.status(ev) == "suspended" then local _, msg = coroutine.resume(ev) if msg then self:say(msg) end end end end -- Play a scripted session ------------------------------------------- local game = Game.new() local script = { "look", "n", "take key", "s", "take lamp", "use lamp", "n", "take key", "dance", "s", "e", "use key", "i", "d" } for _, line in ipairs(script) do game:command(line) if game.over then break end end print(string.format("You won in %d moves carrying: %s", game.moves, table.concat(game.inventory, ", ")))
> look
  Great Hall: Dusty banners hang from the walls.
  You see: lamp
  Exits: east, north
> n
  It is pitch black. You might trip over something.
> take key
  You fumble in the dark.
> s
  Great Hall: Dusty banners hang from the walls.
  You see: lamp
  Exits: east, north
> take lamp
  Taken: lamp
> use lamp
  You light the lamp.
  The shadows retreat. Something glints in the corner.
> n
  Library: Shelves of crumbling books.
  You see: key
  Exits: south
> take key
  Taken: key
> dance
  I don't understand that.
> s
  Great Hall: Dusty banners hang from the walls.
  Exits: east, north
> e
  Kitchen: A cold hearth and a locked trapdoor.
  Exits: west
> use key
  The trapdoor creaks open. Stairs lead down.
> i
  You carry: key, lamp
> d
  Cellar: Barrels of ancient wine. You found the treasure!
  You see: gold
  Exits: up
You won in 13 moves carrying: lamp, key

Walk through the transcript: the library is dark at first, so take key fails; after lighting the lamp the event coroutine adds its message, the room description works, and the key opens the trapdoor. dance isn't a known verb, so it doesn't count as a move.

Make it your own

  • Make the cellar dark too, so that the lamp must be lit to enter it.
  • Add a drop command and a help command that lists sortedKeys(commands).
  • Add a save command using the serializer from step 6 and a load command that restores the state.
  • Move the world data into a separate module (require("world")) and add more rooms.
  • Add a monster whose behaviour is a coroutine that moves it between rooms every few turns.

Test yourself

Why are the game's commands stored in a table of functions?

  1. Tables are faster than functions
  2. Adding a verb means adding one entry, with no long if/elseif chain
  3. Lua has no if statement
  4. To make them global

Why is the saved game loaded with load(saved, "savegame", "t", {})?

  1. To make it faster
  2. The empty environment means the file can only build data, not call functions
  3. Because require can't load strings
  4. To convert it to JSON

What does the lamp event coroutine do on each turn?

  1. Nothing, it runs all at once
  2. It is resumed once and yields the next message
  3. It creates a new room
  4. It saves the game