Menu
Coddy logo textTech

Displaying Exits

Part of the Logic & Flow section of Coddy's Lua journey — lesson 31 of 54.

challenge icon

Challenge

Easy

Enhance the game's user experience by displaying all available exits to the player after showing the room description.

You are provided with the startingRoom, gardenRoom, and player variables from the previous challenge.

Modify the game loop to display available exits:

  • Print the description of the player's current room
  • Print "Exits:" on a new line
  • Use pairs() to iterate through the current room's exits table
  • For each exit, print " - " (two spaces, a dash, and a space) followed by the direction name
  • Print the prompt "> " (greater-than sign followed by a space) without a newline
  • Read the user's command using io.read()
  • Check if the command matches a key in the current room's exits table
  • If it matches, update player.currentRoom to the room stored in that exit
  • If the command does not match any exit and is not "quit", print "You can't go that way."
  • If the command is "quit", set gameRunning to false to exit the loop

The loop should continue until the user types "quit".

Expected Output Format:

You find yourself in a dusty library filled with ancient books and scrolls.
Exits:
  - east
> 
A hidden garden with overgrown plants and a small fountain.
Exits:
  - west
> 
You can't go that way.
A hidden garden with overgrown plants and a small fountain.
Exits:
  - west
> 
You find yourself in a dusty library filled with ancient books and scrolls.
Exits:
  - east
> 

Try it yourself

-- Room definitions
local startingRoom = {
    description = "You find yourself in a dusty library filled with ancient books and scrolls.",
    exits = {}
}

local gardenRoom = {
    description = "A hidden garden with overgrown plants and a small fountain.",
    exits = {}
}

-- Connect rooms
startingRoom.exits["north"] = gardenRoom
gardenRoom.exits["south"] = startingRoom

-- Player
local player = {
    currentRoom = startingRoom
}

-- Game loop
local gameRunning = true

while gameRunning do
    print(player.currentRoom.description)
    io.write("> ")
    local command = io.read()
    
    if command == "quit" then
        gameRunning = false
    elseif player.currentRoom.exits[command] then
        player.currentRoom = player.currentRoom.exits[command]
    else
        print("You can't go that way.")
    end
end

All lessons in Logic & Flow