Menu
CoddyTech

Pętla poleceń: Podsumowanie

Część sekcji Wprowadzenie do Luau ścieżki Lua w Coddy. Lekcja 54 z 80.

challenge icon

Wyzwanie

Średni

Dokończ menedżer zadań, dodając dwa polecenia raportujące.

  1. Po wpisaniu "pending" wyświetl każdy tytuł z filterTasks(tasks, false).
  2. Po wpisaniu "summary" wywołaj printSummary(tasks).

Naciśnij Uruchom kod: po wpisaniu pending, summary, quit wynik pokazuje Learn Luau types, Build a task manager i 1/3 tasks done.

Spróbuj swoich sił

-- Struktura, którą ma każde zadanie w menedżerze
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},
}
-- Utwórz zadanie z następnym wolnym id i dodaj je do listy
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
-- Oznacz zadanie o tym id jako wykonane; poinformuj, czy zostało znalezione
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
-- Nowa lista zadań, których wartość pola done jest zgodna
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
-- Jeden wiersz: ile zadań zostało wykonanych
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
-- Wypróbuj
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

Wszystkie lekcje w sekcji Wprowadzenie do Luau

Poćwicz samodzielnie: Kompilator Luau online