Menu
CoddyTech

コマンドループ:概要

CoddyのLuaジャーニー「Luau入門」セクションの一部。レッスン 54/80。

challenge icon

チャレンジ

中級

2つのレポートコマンドでタスクマネージャーを完成させましょう。

  1. "pending"の場合、filterTasks(tasks, false)の各タイトルを出力します。
  2. "summary"の場合、printSummary(tasks)を呼び出します。

Run Codeを押します。入力が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
-- 完了したタスクの数を 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}`)
    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オンラインコンパイラ