Menu
CoddyTech

Fungsi untuk Mengubah Status Tugas

Termasuk bagian Pengantar Luau dalam perjalanan Lua di Coddy. Pelajaran 47 dari 73.

challenge icon

Tantangan

Mudah

Editor kamu sudah berisi tipe Task, array tasks, dan addTask dari pelajaran sebelumnya.

Buat fungsi bernama completeTask yang menerima dua parameter:

  • list bertipe {Task}
  • id bertipe number

Fungsi tersebut harus:

  • melakukan perulangan pada list dengan ipairs untuk mencari task yang id-nya cocok
  • jika ditemukan, tetapkan done task tersebut ke true dan kembalikan true
  • jika tidak ada task yang cocok, kembalikan false (tipe kembalian boolean)

Lalu cetak, masing-masing pada baris tersendiri:

  1. flag done task pertama (sebelum)
  2. hasil dari completeTask(tasks, 1)
  3. flag done task pertama (sesudah)
  4. hasil dari completeTask(tasks, 99)

Coba sendiri

-- 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)

Semua pelajaran di Pengantar Luau

Latihan sendiri: Compiler Luau online