Menu
Coddy logo textTech

Funkcja: Podsumowanie zadań

Część sekcji Wprowadzenie do Luau ścieżki Lua w Coddy. Lekcja 49 z 73.

challenge icon

Wyzwanie

Łatwy

Twój edytor zawiera już typ Task, tablicę tasks, funkcje addTask, completeTask i filterTasks z poprzednich lekcji.

Utwórz funkcję o nazwie printSummary, która przyjmuje jeden parametr, list typu {Task}, niczego nie zwraca (typ zwracany ()) i wyświetla jeden wiersz w dokładnym formacie:

{doneCount}/{total} tasks done

gdzie total to #list, a doneCount to liczba zadań, dla których done == true (policz je za pomocą pętli).

Następnie użyj całego zestawu narzędzi w tej kolejności:

  1. wywołaj printSummary(tasks)
  2. wywołaj completeTask(tasks, 2)
  3. wywołaj printSummary(tasks)
  4. wywołaj addTask(tasks, "Take a break")
  5. wywołaj printSummary(tasks)

Spróbuj swoich sił

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

-- Collect the tasks whose done flag matches into a new {Task}
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

-- Split the list into pending and finished views
local pending: {Task} = filterTasks(tasks, false)
local finished: {Task} = filterTasks(tasks, true)

print(#pending)
for _, t in ipairs(pending) do
    print(t.title)
end

print(#finished)
for _, t in ipairs(finished) do
    print(t.title)
end

Wszystkie lekcje w sekcji Wprowadzenie do Luau

Poćwicz samodzielnie: Kompilator Luau online