Menu
Coddy logo textTech

Function to Change Task Status

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 47 of 73.

challenge icon

Challenge

Easy

Your editor already contains the Task type, the tasks array and addTask from the previous lessons.

Create a function named completeTask that takes two parameters:

  • list of type {Task}
  • id of type number

The function should:

  • loop over list with ipairs looking for a task whose id matches
  • if found, set that task's done to true and return true
  • if no task matches, return false (return type boolean)

Then print, each on its own line:

  1. the first task's done flag (before)
  2. the result of completeTask(tasks, 1)
  3. the first task's done flag (after)
  4. the result of completeTask(tasks, 99)

Try it yourself

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

All lessons in Introduction To Luau