Menu
CoddyTech

Loop de Comandos: Listar e Concluir

Parte da seção Introdução ao Luau do Journey de Lua da Coddy. Lição 53 de 80.

challenge icon

Desafio

Médio

Adicione um comando que liste as tarefas e outro que as conclua.

  1. Ao receber "list", imprima cada tarefa como `[x] {t.title}` quando estiver concluída; caso contrário, como `[ ] {t.title}`.
  2. Ao receber "done", leia local id: number = tonumber(io.read()) or 0; imprima `Task {id} completed` se completeTask(tasks, id) for true; caso contrário, imprima `No task with id {id}`.

Pressione Executar código: com a entrada done, 2, quit, a saída mostra Task 2 completed.

Experimente você mesmo

-- A estrutura que todas as tarefas do gerenciador seguem
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},
}
-- Crie uma tarefa com o próximo id disponível e adicione-a à lista
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
-- Marque a tarefa com este id como concluída; informe se alguma foi encontrada
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
-- Uma nova lista das tarefas cujo valor de done corresponde ao solicitado
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
-- Uma linha: quantas tarefas estão concluídas
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
-- Experimente
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

Todas as lições de Introdução ao Luau

Pratique por conta própria: Compilador de Luau online