Menu
Coddy logo textTech

Function: List Tasks by Status

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

challenge icon

Challenge

Easy

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

Create a function named filterTasks that takes two parameters:

  • list of type {Task}
  • done of type boolean

The function should build and return a new array of type {Task} containing only the tasks whose done flag equals the parameter.

Then:

  1. store filterTasks(tasks, false) in pending and filterTasks(tasks, true) in finished
  2. print #pending, then each pending task's title on its own line (use ipairs)
  3. print #finished, then each finished task's title on its own line

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

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

All lessons in Introduction To Luau