Menu
Coddy logo textTech

Lister tous les contacts

Fait partie de la section Logique et flux du Journey Lua de Coddy. Leçon 44 sur 54.

challenge icon

Défi

Facile

Implémentez la fonctionnalité d’affichage de la liste pour votre application de liste de contacts. Lorsque l’utilisateur saisit list, le programme doit afficher tous les contacts enregistrés dans un format structuré.

En vous appuyant sur le défi précédent, ajoutez une fonctionnalité pour gérer la commande list. Utilisez ipairs() pour parcourir la table contacts et afficher les informations de chaque contact. Si la liste est vide, informez-en l’utilisateur.

Exigences :

  • Conservez tout le code du défi précédent (configuration, affichage du menu, boucle principale et fonctionnalité d’ajout)
  • Lorsque l’utilisateur saisit list, vérifiez si la table contacts est vide
  • Si elle est vide, affichez : No contacts found.
  • Si elle ne l’est pas, affichez : Contact List:
  • Utilisez ipairs() pour parcourir la table contacts
  • Pour chaque contact, affichez les informations au format : [index]. [name] - [phone]
  • Les commandes add et quit doivent continuer à fonctionner comme précédemment
  • Les autres commandes doivent continuer à afficher Command not yet implemented

Exemple d’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!

Essayez vous-même

-- 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

Toutes les leçons de Logique et flux

Entraînez-vous par vous-même : Compilateur Lua en ligne