Menu
Coddy logo textTech

Funzione per modificare lo stato di un'attività

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

challenge icon

Sfida

Facile

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

Crea una funzione chiamata completeTask che accetta due parametri:

  • list di tipo {Task}
  • id di tipo number

La funzione dovrebbe:

  • scorrere list con ipairs cercando un’attività il cui id corrisponda
  • se viene trovata, impostare done di quell’attività su true e restituire true
  • se nessuna attività corrisponde, restituire false (tipo restituito boolean)

Poi stampa, ciascuno su una riga:

  1. il flag done della prima attività (prima)
  2. il risultato di completeTask(tasks, 1)
  3. il flag done della prima attività (dopo)
  4. il risultato di completeTask(tasks, 99)

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

-- Add a task and inspect what came back
local added: Task = addTask(tasks, "Review the code")
print(#tasks)
print(added.id)
print(added.title)
print(added.done)

Tutte le lezioni di Introduzione a Luau

Esercitati da solo: Compilatore Luau online