Menu
CoddyTech

Vòng lặp lệnh: bản tóm tắt

Thuộc phần Giới thiệu về Luau trong hành trình Lua của Coddy. Bài học 54 trên 80.

challenge icon

Thử thách

Trung bình

Hoàn thiện trình quản lý công việc bằng hai lệnh báo cáo.

  1. Với "pending", in ra từng tiêu đề trong filterTasks(tasks, false).
  2. Với "summary", gọi printSummary(tasks).

Nhấn Run Code: với đầu vào pending, summary, quit, đầu ra hiển thị Learn Luau types, Build a task manager và 1/3 tasks done.

Tự làm thử

-- Cấu trúc mà mọi công việc trong trình quản lý đều tuân theo
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},
}
-- Tạo công việc với id chưa dùng tiếp theo và thêm vào danh sách
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
-- Đánh dấu công việc có id này là đã xong; cho biết có tìm thấy công việc đó không
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
-- Danh sách mới gồm các công việc có giá trị done khớp với giá trị cần lọc
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
-- Một dòng cho biết có bao nhiêu công việc đã xong
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
-- Thử chạy
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}`)
    elseif command == "list" then
        for _, t in ipairs(tasks) do
            if t.done then
                print(`[x] {t.title}`)
            else
                print(`[ ] {t.title}`)
            end
        end
    elseif command == "done" then
        local id: number = tonumber(io.read()) or 0
        if completeTask(tasks, id) then
            print(`Task {id} completed`)
        else
            print(`No task with id {id}`)
        end
    end
end

Tất cả bài học trong Giới thiệu về Luau

Tự luyện tập: Trình biên dịch Luau online