Menu
CoddyTech

コマンドループ:追加

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

challenge icon

チャレンジ

中級

ツールキットがコマンドを読み取るようにします。

  1. -- Try itの下にある行を削除します。
  2. その下でwhile true doを使ってループし、local command = io.read()で読み取ります。nilまたは"quit"の場合はbreakします。
  3. "add"の場合は、タイトルを読み取り、local added: Task = addTask(tasks, title)に保存して、`Added task {added.id}: {added.title}`を出力します。

「コードを実行」を押します。入力がaddとShip itの場合、出力にはAdded task 4: Ship itと表示されます。

自分で試してみよう

-- マネージャー内のすべてのタスクが従う形式
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
-- 試してみる
printSummary(tasks)
completeTask(tasks, 2)
printSummary(tasks)

Luau入門のすべてのレッスン

自分で練習してみよう: Luauオンラインコンパイラ