Menu
CoddyTech

Liệt kê tất cả liên hệ

Thuộc phần Logic và luồng chương trình trong hành trình Lua của Coddy. Bài học 44 trên 54.

challenge icon

Thử thách

Dễ

Triển khai chức năng liệt kê cho ứng dụng danh sách liên hệ. Khi người dùng nhập list, chương trình sẽ hiển thị tất cả liên hệ đã lưu theo định dạng dễ đọc.

Dựa trên thử thách trước, hãy thêm chức năng xử lý lệnh list. Dùng ipairs() để duyệt qua bảng contacts và hiển thị thông tin của từng liên hệ. Nếu danh sách trống, hãy thông báo cho người dùng.

Yêu cầu:

  • Giữ lại toàn bộ code từ thử thách trước (phần thiết lập, hiển thị menu, vòng lặp chính và chức năng thêm liên hệ)
  • Khi người dùng nhập list, hãy kiểm tra xem bảng contacts có trống không
  • Nếu trống, in ra: No contacts found.
  • Nếu không trống, in ra: Contact List:
  • Dùng ipairs() để duyệt qua bảng contacts
  • Với mỗi liên hệ, in theo định dạng: [index]. [name] - [phone]
  • Các lệnh add và quit vẫn hoạt động như trước
  • Các lệnh khác vẫn in ra Command not yet implemented

Tương tác mẫu:

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!

Tự làm thử

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

Tất cả bài học trong Logic và luồng chương trình

Tự luyện tập: Trình biên dịch Lua online