Menu
Coddy logo textTech

Listing All Contacts

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

challenge icon

Challenge

Easy

Implement 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 the contacts table is empty
  • If empty, print: No contacts found.
  • If not empty, print: Contact List:
  • Use ipairs() to iterate through the contacts table
  • For each contact, print in the format: [index]. [name] - [phone]
  • The add and quit commands 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
end

All lessons in Logic & Flow