Menu
CoddyTech

Function: List Tasks by Status

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 50 of 80.

challenge icon

Challenge

Easy

Add a function that picks out tasks by their status.

  1. Delete the lines under -- Try it.
  2. Write local function filterTasks(list: {Task}, done: boolean): {Task} that returns a new list of the tasks whose done equals the parameter.
  3. Under -- Try it, store filterTasks(tasks, false) in local pending, then print #pending and pending[2].title.

Press Run Code: the output shows 2 and Build a task manager.

Try it yourself

-- The shape every task in the manager follows
type Task = {
    id: number,
    title: string,
    done: boolean,
}
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 task with the next free id and add it to the list
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 this id as done; say whether one was found
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
-- Try it
print(completeTask(tasks, 1))
print(tasks[1].done)
print(completeTask(tasks, 99))

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler