Menu
CoddyTech

Command Loop: List and Done

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

challenge icon

Challenge

Medium

Add a command that lists tasks and one that completes them.

  1. On "list", print each task as `[x] {t.title}` when done, otherwise `[ ] {t.title}`.
  2. On "done", read local id: number = tonumber(io.read()) or 0; print `Task {id} completed` if completeTask(tasks, id) is true, otherwise `No task with id {id}`.

Press Run Code: with the input done, 2, quit, the output shows Task 2 completed.

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
-- A new list of the tasks whose done flag matches
local function filterTasks(list: {Task}, done: boolean): {Task}
    local result: {Task} = {}
    for _, t in ipairs(list) do
        if t.done == done then
            table.insert(result, t)
        end
    end
    return result
end
-- One line: how many tasks are done
local function printSummary(list: {Task}): ()
    local doneCount = 0
    for _, t in ipairs(list) do
        if t.done then
            doneCount += 1
        end
    end
    print(`{doneCount}/{#list} tasks done`)
end
-- Try it
while true do
    local command = io.read()
    if command == nil or command == "quit" then
        break
    elseif command == "add" then
        local title = io.read()
        local added: Task = addTask(tasks, title)
        print(`Added task {added.id}: {added.title}`)
    end
end

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler