コマンドループ:一覧と完了
CoddyのLuaジャーニー「Luau入門」セクションの一部。レッスン 53/80。
チャレンジ
中級タスクを一覧表示するコマンドと、タスクを完了にするコマンドを追加します。
"list"の場合、完了済みなら各タスクを`[x] {t.title}`として、それ以外は`[ ] {t.title}`として出力します。"done"の場合、local id: number = tonumber(io.read()) or 0を読み込みます。completeTask(tasks, id)がtrueなら`Task {id} completed`を、それ以外なら`No task with id {id}`を出力します。
Run Codeを押します。入力がdone、2、quitの場合、出力にはTask 2 completedと表示されます。
自分で試してみよう
-- マネージャー内のすべてのタスクが従う形式
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
-- 完了したタスクの数を1行で表示する
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}`)
end
end
Luau入門のすべてのレッスン
7プロジェクト:型付きタスク管理ツール
プロジェクト:タスクの構造タスクを追加する関数自分で練習してみよう: Luauオンラインコンパイラ