Menu
CoddyTech

명령 루프: 요약

Coddy Lua 여정의 Luau 소개 섹션에 포함된 레슨. 80개 중 54번째.

challenge icon

챌린지

중급

두 개의 보고 명령을 추가해 작업 관리자를 완성하세요.

  1. "pending"이 입력되면 filterTasks(tasks, false)의 각 제목을 출력하세요.
  2. "summary"가 입력되면 printSummary(tasks)를 호출하세요.

코드 실행을 누르세요. 입력값이 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 컴파일러