Menu
CoddyTech

Komut Döngüsü: Özet

Coddy'nin Lua Journey'sinin Luau'ya Giriş bölümünün bir parçası. Ders 54 / 80.

challenge icon

Görev

Orta

Görev yöneticisini iki rapor komutuyla tamamla.

  1. "pending" komutunda, filterTasks(tasks, false) içindeki her başlığı yazdır.
  2. "summary" komutunda, printSummary(tasks) işlevini çağır.

Run Code düğmesine bas: pending, summary, quit girdileriyle çıktıda Learn Luau types, Build a task manager ve 1/3 tasks done görünür.

Kendin dene

-- Yöneticideki her görevin uyduğu yapı
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},
}
-- Sonraki boş id ile bir görev oluştur ve listeye ekle
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
-- Bu id'ye sahip görevi tamamlandı olarak işaretle; böyle bir görev bulunup bulunmadığını belirt
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 değeri eşleşen görevlerden oluşan yeni bir liste
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
-- Tek satırda: kaç görev tamamlandı
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
-- Dene
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'ya Giriş bölümündeki tüm dersler

Kendi başına pratik yap: Online Luau derleyicisi