Menu
Coddy logo textTech

Mettere tutto insieme

Fa parte della sezione Introduzione a Luau del percorso Lua di Coddy. Lezione 50 di 73.

challenge icon

Sfida

Medio

Il tuo editor contiene già il kit completo: il tipo Task, l’array tasks (tre attività iniziali), addTask, completeTask, filterTasks e printSummary.

Scrivi un ciclo di comandi che continui a leggere una riga con io.read() e gestisca questi comandi:

  • add: leggi un’altra riga come titolo, chiama addTask e stampa esattamente: Added task {id}: {title} (usando i campi dell’attività restituita)
  • done: leggi un’altra riga, convertila con tonumber(...) or 0, chiama completeTask; stampa Task {id} completed se ha restituito true, altrimenti No task with id {id}
  • list: per ogni attività, stampa [x] {title} se è completata, altrimenti [ ] {title} (nota lo spazio)
  • pending: stampa il titolo di ogni attività incompleta, usando filterTasks
  • summary: chiama printSummary(tasks)
  • quit: interrompi il ciclo (interrompilo anche se io.read() restituisce nil)

Provalo tu

-- The shape every task in the manager must follow
type Task = {
    id: number,
    title: string,
    done: boolean,
}

-- The task list: a typed array of Task shapes
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},
}

-- Build a typed task with the next free id and insert it
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

-- Mark the task with the given id as done; report success
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

-- Collect the tasks whose done flag matches into a new {Task}
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

-- Print a one-line progress summary
local function printSummary(list: {Task}): ()
    local total = #list
    local doneCount = 0
    for _, t in ipairs(list) do
        if t.done then
            doneCount = doneCount + 1
        end
    end
    print(`{doneCount}/{total} tasks done`)
end

-- Watch the summary change as the list evolves
printSummary(tasks)
completeTask(tasks, 2)
printSummary(tasks)
addTask(tasks, "Take a break")
printSummary(tasks)

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online