命令循环:摘要
本课属于 Coddy Lua 学习旅程的“Luau 入门”单元。第 54 课,共 80 课。
挑战
中等为任务管理器添加两个报告命令,完成它。
- 收到
"pending"时,打印filterTasks(tasks, false)中的每个标题。 - 收到
"summary"时,调用printSummary(tasks)。
按下 运行代码:输入 pending、summary、quit 后,输出会显示 Learn Luau types、Build a task manager 和 1/3 tasks done。
亲手试试
-- 管理器中每个任务都遵循的数据结构
type Task = {
id: number,
title: string,
done: boolean,
}
local tasks: {Task} = {
{id = 1, title = "Learn Luau types", done = false},
{id = 2, title = "Build a task manager", done = false},
{id = 3, title = "Write tests", done = true},
}
-- 用下一个可用的 id 创建任务,并将其添加到列表中
local function addTask(list: {Task}, title: string): Task
local newTask: Task = {id = #list + 1, title = title, done = false}
table.insert(list, newTask)
return newTask
end
-- 将具有此 id 的任务标记为完成,并返回是否找到了该任务
local function completeTask(list: {Task}, id: number): boolean
for _, t in ipairs(list) do
if t.id == id then
t.done = true
return true
end
end
return false
end
-- 包含 done 值相符的任务的新列表
local function filterTasks(list: {Task}, done: boolean): {Task}
local result: {Task} = {}
for _, t in ipairs(list) do
if t.done == done then
table.insert(result, t)
end
end
return result
end
-- 用一行输出已完成的任务数量
local function printSummary(list: {Task}): ()
local doneCount = 0
for _, t in ipairs(list) do
if t.done then
doneCount += 1
end
end
print(`{doneCount}/{#list} tasks done`)
end
-- 试一试
while true do
local command = io.read()
if command == nil or command == "quit" then
break
elseif command == "add" then
local title = io.read()
local added: Task = addTask(tasks, title)
print(`Added task {added.id}: {added.title}`)
elseif command == "list" then
for _, t in ipairs(tasks) do
if t.done then
print(`[x] {t.title}`)
else
print(`[ ] {t.title}`)
end
end
elseif command == "done" then
local id: number = tonumber(io.read()) or 0
if completeTask(tasks, id) then
print(`Task {id} completed`)
else
print(`No task with id {id}`)
end
end
end
Luau 入门中的所有课
自己练习: Luau 在线编译器