Adding a Contact
Part of the Logic & Flow section of Coddy's Lua journey — lesson 43 of 54.
Challenge
EasyImplement the contact addition feature for your contact list application. When the user enters add, the program should prompt for contact details and store them in the contacts list.
Building on the previous main loop, add functionality to handle the add command. When this command is entered, prompt the user for a name and phone number, create a contact table with these details, and add it to the contacts list using table.insert().
Requirements:
- Keep all code from the previous challenge (setup, menu display, and main loop)
- When the user enters
add, print:Enter name: - Read the name using
io.read() - Print:
Enter phone number: - Read the phone number using
io.read() - Create a dictionary-style table with keys
nameandphone - Insert this contact table into the
contactslist usingtable.insert() - Print:
Contact added successfully! - The
quitcommand should still work as before - Other commands should still print
Command not yet implemented
Example interaction:
Welcome to Contact List Manager!
Available Commands:
add - Add a new contact
list - Display all contacts
search - Search for a contact
delete - Delete a contact
quit - Exit the program
Enter command:
add
Enter name:
Alice
Enter phone number:
555-1234
Contact added successfully!
Enter command:
add
Enter name:
Bob
Enter phone number:
555-5678
Contact added successfully!
Enter command:
list
Command not yet implemented
Enter command:
quit
Goodbye!Try it yourself
-- Initialize the contacts table
local contacts = {}
-- Display welcome message and menu
print("Welcome to Contact List Manager!")
print()
print("Available Commands:")
print("add - Add a new contact")
print("list - Display all contacts")
print("search - Search for a contact")
print("delete - Delete a contact")
print("quit - Exit the program")
print()
-- Main program loop
while true do
print("Enter command:")
local command = io.read()
if command == "quit" then
print("Goodbye!")
break
else
print("Command not yet implemented")
end
print()
endAll 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 Rooms8Project: Contact List
Project SetupThe Main Loop