添加联系人
本课属于 Coddy Lua 学习旅程的“逻辑与流程”单元。第 43 课,共 54 课。
挑战
简单为你的联系人列表应用实现添加联系人的功能。当用户输入 add 时,程序应提示用户输入联系人详细信息,并将其存储在联系人列表中。
在上一个主循环的基础上,添加处理 add 命令的功能。输入此命令后,提示用户输入姓名和电话号码,用这些信息创建一个联系人表,并使用 table.insert() 将其添加到 contacts 列表中。
要求:
- 保留上一个挑战中的所有代码(初始化、显示菜单和主循环)
- 用户输入
add时,打印:Enter name: - 使用
io.read()读取姓名 - 打印:
Enter phone number: - 使用
io.read()读取电话号码 - 创建一个字典式的表,其中包含
name和phone键 - 使用
table.insert()将此联系人表插入contacts列表中 - 打印:
Contact added successfully! quit命令仍应像之前一样正常工作- 其他命令仍应打印
Command not yet implemented
交互示例:
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!亲手试试
-- 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()
end逻辑与流程中的所有课
自己练习: Lua 在线编译器