Menu
Coddy logo textTech

Funzione: Elencare le attività per stato

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

challenge icon

Sfida

Facile

Il tuo editor contiene già il tipo Task, l’array tasks, addTask e completeTask delle lezioni precedenti.

Crea una funzione chiamata filterTasks che accetta due parametri:

  • list di tipo {Task}
  • done di tipo boolean

La funzione dovrebbe creare e restituire un nuovo array di tipo {Task} contenente solo le attività il cui flag done è uguale al parametro.

Poi:

  1. memorizza filterTasks(tasks, false) in pending e filterTasks(tasks, true) in finished
  2. stampa #pending, poi il titolo di ogni attività in sospeso su una riga separata (usa ipairs)
  3. stampa #finished, poi il titolo di ogni attività completata su una riga separata

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

-- Complete task 1, then try an id that doesn't exist
print(tasks[1].done)
print(completeTask(tasks, 1))
print(tasks[1].done)
print(completeTask(tasks, 99))

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online