Menu
CoddyTech

Ciclo dei comandi: Riepilogo

Fa parte della sezione Introduzione a Luau del percorso Lua di Coddy. Lezione 54 di 80.

challenge icon

Sfida

Medio

Completa il gestore delle attività con due comandi di riepilogo.

  1. Con "pending", stampa ogni titolo in filterTasks(tasks, false).
  2. Con "summary", chiama printSummary(tasks).

Premi Esegui codice: con l’input pending, summary, quit, l’output mostra Learn Luau types, Build a task manager e 1/3 tasks done.

Provalo tu

-- La struttura seguita da ogni attività nel gestore
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},
}
-- Crea un'attività con il prossimo id disponibile e aggiungila alla lista
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
-- Segna come completata l'attività con questo id; indica se ne è stata trovata una
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
-- Una nuova lista delle attività per cui il valore di done corrisponde
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
-- Una riga: quante attività sono completate
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
-- Provalo
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

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online