Menu
CoddyTech

Ciclo dei comandi: Elencare e completare

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

challenge icon

Sfida

Medio

Aggiungi un comando che elenca le attività e uno che le completa.

  1. Con "list", stampa ogni attività come `[x] {t.title}` se è completata, altrimenti come `[ ] {t.title}`.
  2. Con "done", leggi local id: number = tonumber(io.read()) or 0; stampa `Task {id} completed` se completeTask(tasks, id) è true, altrimenti `No task with id {id}`.

Premi Run Code: con l'input done, 2, quit, l'output mostra Task 2 completed.

Provalo tu

-- La struttura che ogni attività nel gestore deve seguire
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à il cui valore 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}`)
    end
end

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online