Menu
CoddyTech

حلقة الأوامر: ملخص

جزء من قسم مقدمة إلى Luau في رحلة Lua على Coddy. الدرس 54 من 80.

challenge icon

التحدي

متوسط

أكمِل مدير المهام بأمري أمر التقارير.

  1. عند إدخال "pending"، اطبع كل عنوان في filterTasks(tasks, false).
  2. عند إدخال "summary"، استدعِ printSummary(tasks).

اضغط على Run Code: عند إدخال pending وsummary وquit، سيعرض الناتج Learn Luau types وBuild a task manager و1/3 tasks done.

جرّب بنفسك

-- البنية التي تتبعها كل مهمة في المدير
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},
}
-- أنشئ مهمة باستخدام قيمة id التالية المتاحة وأضفها إلى القائمة
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
-- ضع علامة على المهمة ذات قيمة id هذه بأنها مكتملة؛ وبيّن ما إذا عُثر عليها
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
-- قائمة جديدة بالمهام التي تتطابق قيمة done فيها
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
-- سطر واحد: عدد المهام المكتملة
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
-- جرّبه
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

جميع دروس مقدمة إلى Luau

تدرّب بنفسك: مترجم Luau عبر الإنترنت