Listing All Contacts
Part of the Logic & Flow section of Coddy's Lua journey — lesson 44 of 54.
Challenge
EasyImplement the list functionality for your contact list application. When the user enters list, the program should display all stored contacts in a formatted way.
Building on the previous challenge, add functionality to handle the list command. Use ipairs() to iterate through the contacts table and display each contact's information. If the list is empty, inform the user accordingly.
Requirements:
- Keep all code from the previous challenge (setup, menu display, main loop, and add functionality)
- When the user enters
list, check if thecontactstable is empty - If empty, print:
No contacts found. - If not empty, print:
Contact List: - Use
ipairs()to iterate through thecontactstable - For each contact, print in the format:
[index]. [name] - [phone] - The
addandquitcommands 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:
list
No contacts found.
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
Contact List:
1. Alice - 555-1234
2. Bob - 555-5678
Enter command:
quit
Goodbye!Try it yourself
-- Initialize contacts list
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 loop
while true do
print("Enter command:")
local command = io.read()
if command == "add" then
print("Enter name:")
local name = io.read()
print("Enter phone number:")
local phone = io.read()
local contact = {name = name, phone = phone}
table.insert(contacts, contact)
print("Contact added successfully!")
print()
elseif command == "quit" then
print("Goodbye!")
break
else
print("Command not yet implemented")
print()
end
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