코루틴 상태
coroutine.status로 코루틴 상태인 running, suspended, dead를 확인합니다.
코루틴 상태은(는) CoddyKit의 무료 Lua Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Lua Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Lua Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
코루틴의 네 가지 상태
코루틴에는 네 가지 가능한 상태가 있습니다. 일시 중단(생성되었거나 yield되어 실행을 기다리는 상태), 실행 중(현재 실행 중인 상태), 일반(다른 코루틴을 실행하도록 일시 중지된 상태), 종료(실행을 마쳤거나 오류가 발생한 상태)입니다. coroutine.status(co)로 조회할 수 있습니다.
local co = coroutine.create(function()
print(coroutine.status(coroutine.running())) -- running
coroutine.yield()
end)
print(coroutine.status(co)) -- suspended
coroutine.resume(co) -- prints: running
print(coroutine.status(co)) -- suspended
coroutine.resume(co)
print(coroutine.status(co)) -- dead"일반" 상태
코루틴이 다른 코루틴을 재개하면 "일반" 상태가 됩니다. 이 코루틴은 실행 중이 아닙니다(다른 코루틴이 실행 중이기 때문). 그렇다고 일시 중단된 것도 아닙니다. 재개된 코루틴이 yield할 때까지 기다리는 상태입니다. 이 상태는 드물지만 복잡한 코루틴 그래프를 이해하려면 중요합니다.
local inner, outer
inner = coroutine.create(function()
print("outer status:", coroutine.status(outer)) -- normal
coroutine.yield()
end)
outer = coroutine.create(function()
coroutine.resume(inner)
end)
coroutine.resume(outer)
-- prints: outer status: normal재개 전 확인
특히 반복문에서는 코루틴을 재개하기 전에 항상 상태를 확인하십시오. 종료된 코루틴을 재개하면 오류가 발생합니다. 실행 중인 코루틴을 재개하는 것도 오류입니다(무한 재귀가 발생하기 때문입니다).
local function safeResume(co, ...)
local status = coroutine.status(co)
if status == "dead" then
return false, "cannot resume dead coroutine"
end
if status == "running" then
return false, "cannot resume running coroutine"
end
return coroutine.resume(co, ...)
end오류 후 상태
코루틴 본문에서 처리되지 않은 오류가 발생하면 coroutine.resume은 false와 오류 메시지를 반환합니다. 코루틴은 "종료" 상태로 전환됩니다. 코루틴을 다시 시작할 수는 없습니다. 다시 시도하려면 새 코루틴을 생성해야 합니다.
local co = coroutine.create(function()
error("something went wrong")
end)
local ok, err = coroutine.resume(co)
print(ok, err) -- false ...: something went wrong
print(coroutine.status(co)) -- dead
-- Cannot resume dead coroutine:
local ok2, err2 = coroutine.resume(co)
print(ok2, err2) -- false cannot resume dead coroutinecoroutine.isyieldable
coroutine.isyieldable()은 실행 중인 코루틴이 yield할 수 있으면 true를 반환합니다. 메인 스레드와 yield를 지원하지 않는 C 함수에서는 false를 반환합니다. 현재 컨텍스트가 확실하지 않다면 yield하기 전에 항상 확인하십시오.
local co = coroutine.create(function()
print("isyieldable:", coroutine.isyieldable()) -- true
coroutine.yield()
end)
coroutine.resume(co)
-- In main thread:
print("isyieldable:", coroutine.isyieldable()) -- false
-- coroutine.yield() -- ERROR in main thread코루틴 집합 모니터링
코루틴 풀을 추적하고, 재개를 반복한 각 라운드가 끝난 후 종료된 코루틴을 제거하십시오. 이것이 작업 스케줄러의 기반입니다.
local function makeWorker(n, name)
return coroutine.create(function()
for i = 1, n do
print(name, "step", i)
coroutine.yield()
end
end)
end
local workers = {
makeWorker(2, "fast"),
makeWorker(4, "slow"),
}
while #workers > 0 do
local alive = {}
for _, co in ipairs(workers) do
coroutine.resume(co)
if coroutine.status(co) ~= "dead" then
alive[#alive+1] = co
end
end
workers = alive
end코루틴 디버깅
상태 확인을 사용하여 코루틴 기반 코드를 계측하고 디버깅하십시오. 흐름을 이해할 수 있도록 상태 전환을 출력하십시오. 복잡한 시스템에서는 래퍼 테이블을 통해 코루틴에 이름을 지정하면 디버깅 출력이 더 읽기 쉬워집니다.
local function namedCo(name, fn)
local co = coroutine.create(fn)
return {
co = co,
name = name,
resume = function(self, ...)
print("[" .. self.name .. "] resume")
local results = table.pack(coroutine.resume(self.co, ...))
print("[" .. self.name .. "] status: " .. coroutine.status(self.co))
return table.unpack(results, 1, results.n)
end
}
end
local worker = namedCo("worker1", function()
coroutine.yield()
end)
worker:resume()
worker:resume()종료된 코루틴 다시 시작
코루틴이 종료되면 다시 재개할 수 없습니다. 코루틴을 "다시 시작"하려면 같은 함수로 새 코루틴을 생성해야 합니다. 필요할 때마다 새 코루틴을 생성하는 팩토리를 사용하는 것이 일반적인 패턴입니다.
local function makeCounter(start, step)
return coroutine.wrap(function()
local n = start or 0
while true do
coroutine.yield(n)
n = n + (step or 1)
end
end)
end
local count = makeCounter(0, 2)
for i = 1, 5 do io.write(count() .. " ") end
print() -- 0 2 4 6 8
-- "Restart" by creating a new one
count = makeCounter(100)
print(count()) -- 100Coroutine.wrap의 오류 동작
래핑된 코루틴에서 오류가 발생하면 오류가 래퍼 함수 호출 밖으로 전파됩니다. false와 오류를 반환하는 coroutine.resume과 달리, wrap이 반환한 함수는 오류를 직접 발생시킵니다. 오류를 포착해야 한다면 wrap 호출을 pcall로 감싸십시오.
local gen = coroutine.wrap(function()
coroutine.yield(1)
error("oops")
coroutine.yield(2) -- never reached
end)
print(gen()) -- 1 (ok)
local ok, err = pcall(gen)
print(ok, err) -- false ...: oops
-- Subsequent call: dead coroutine
ok, err = pcall(gen)
print(ok, err) -- false cannot resume dead coroutineisyieldable과 status 비교
코루틴 컨텍스트를 확인하는 두 가지 방법이 있습니다. coroutine.status(co)는 특정 코루틴의 상태를 알려 주고, coroutine.isyieldable()은 현재 실행 컨텍스트가 yield할 수 있는지 알려 줍니다. 다른 코루틴을 확인할 때는 status를 사용하고, 안전하게 yield할 수 있는지 확인할 때는 isyieldable을 사용하십시오.
local function maybeYield()
if coroutine.isyieldable() then
coroutine.yield()
else
-- in main thread or non-yieldable context
print("cannot yield here")
end
end
maybeYield() -- prints "cannot yield here" (main thread)
local co = coroutine.create(maybeYield)
coroutine.resume(co) -- yields successfully빠른 확인
코루틴은 본문 함수의 실행을 마치면 어떤 상태가 됩니까?
복습: 코루틴 상태
요약:
- 상태: 일시 중단 → 실행 중 ↔ 일반 → 종료
coroutine.status(co)는 상태 문자열을 반환합니다- 종료 = 실행 완료 또는 오류 발생, 다시 재개할 수 없음
coroutine.isyieldable()은 현재 컨텍스트가 yield할 수 있는지 확인합니다- 반복문에서 재개하기 전에는 항상 상태를 확인하십시오
- wrap의 오류는 직접 전파되고, resume은 false+err을 반환합니다
자주 묻는 질문
“코루틴 상태” 강의는 무료인가요?
네 — “코루틴 상태” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Lua Academy 강의 전체를 잠금 해제할 수 있습니다. Lua Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“코루틴 상태”에서 뭘 배우나요?
coroutine.status로 코루틴 상태인 running, suspended, dead를 확인합니다. 브라우저에서 직접 실행하는 실습 코드로 Lua Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Lua Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Lua Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“코루틴 상태” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Lua Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Lua Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.