Handling Invalid Moves
Part of the Logic & Flow section of Coddy's Lua journey. Lesson 30 of 54.
Challenge
EasyAdd error handling to the movement system to provide feedback when the player enters an invalid direction.
You are provided with the startingRoom, gardenRoom, and player variables from the previous challenge.
Modify the game loop to handle invalid movement commands:
- Replace the previous challenge's east/west exits with north/south exits: set
startingRoom.exits["north"]togardenRoom, andgardenRoom.exits["south"]tostartingRoom - Print the description of the player's current room
- 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
exitstable - If it matches, update
player.currentRoomto 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", setgameRunningtofalseto 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.
> A hidden garden with overgrown plants and a small fountain.
> You can't go that way.
A hidden garden with overgrown plants and a small fountain.
> You find yourself in a dusty library filled with ancient books and scrolls.
> 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 = {}
}
-- TODO: Connect the rooms with north/south exits
-- Player
local player = {
currentRoom = startingRoom
}
-- Game loop
local gameRunning = true
-- TODO: Write the while loop here
All lessons in Logic & Flow
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board5Project: Text Adventure Engine
Project Setup: The RoomLinking RoomsPractice on your own: Online Lua compiler