Menu
Coddy logo textTech

מחברים הכול יחד

חלק מהיחידה מבוא ל-Luau במסלול ה-Lua של Coddy. שיעור 50 מתוך 73.

challenge icon

אתגר

בינוני

העורך שלך כבר מכיל את כל הכלים: הטיפוס Task, המערך tasks (שלוש משימות התחלתיות), addTask, completeTask, filterTasks ו־printSummary.

כתוב לולאת פקודות שקוראת שוב ושוב שורה באמצעות io.read() ומטפלת בפקודות הבאות:

  • add: קרא שורה נוספת בתור הכותרת, קרא ל־addTask והדפס בדיוק: Added task {id}: {title} (באמצעות השדות של המשימה שהוחזרה)
  • done: קרא שורה נוספת, המר אותה באמצעות tonumber(...) or 0, קרא ל־completeTask; הדפס Task {id} completed אם הוחזר true, אחרת הדפס No task with id {id}
  • list: עבור כל משימה, הדפס [x] {title} אם היא הושלמה, אחרת הדפס [ ] {title} (שימו לב לרווח)
  • pending: הדפס את הכותרת של כל משימה שלא הושלמה, באמצעות filterTasks
  • summary: קרא ל־printSummary(tasks)
  • quit: עצור את הלולאה (עצור גם אם io.read() מחזירה nil)

נסו בעצמכם

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

-- Print a one-line progress summary
local function printSummary(list: {Task}): ()
    local total = #list
    local doneCount = 0
    for _, t in ipairs(list) do
        if t.done then
            doneCount = doneCount + 1
        end
    end
    print(`{doneCount}/{total} tasks done`)
end

-- Watch the summary change as the list evolves
printSummary(tasks)
completeTask(tasks, 2)
printSummary(tasks)
addTask(tasks, "Take a break")
printSummary(tasks)

כל השיעורים ביחידה מבוא ל-Luau

תרגלו בעצמכם: קומפיילר Luau אונליין