코루틴 만들기
coroutine.create와 coroutine.wrap으로 코루틴을 만듭니다.
코루틴 만들기은(는) CoddyKit의 무료 Lua Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Lua Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Lua Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
코루틴이란 무엇입니까
코루틴은 실행을 일시 중지(yield)한 다음 중단한 지점에서 다시 시작할 수 있는 함수입니다. 스레드와 달리 코루틴은 협력적입니다. 한 번에 하나만 실행되며 명시적으로 제어권을 양보합니다. Lua 코루틴은 자체 스택과 로컬 변수를 가집니다.
local co = coroutine.create(function()
print("start")
coroutine.yield()
print("resumed")
coroutine.yield()
print("done")
end)
print(coroutine.status(co)) -- suspended
coroutine.resume(co) -- start
print(coroutine.status(co)) -- suspended
coroutine.resume(co) -- resumedcoroutine.create와 coroutine.wrap
coroutine.create(fn)은 코루틴을 만들고 코루틴 객체(thread 형식)를 반환합니다. coroutine.wrap(fn)은 코루틴을 만들고, 호출할 때마다 코루틴을 resume하는 함수를 반환합니다. wrap은 더 간단하지만 코루틴 객체를 숨깁니다.
-- create: returns coroutine object
local co = coroutine.create(function(x)
return x * 2
end)
local ok, val = coroutine.resume(co, 5)
print(ok, val) -- true 10
-- wrap: returns a resumable function
local gen = coroutine.wrap(function(x)
return x * 3
end)
print(gen(5)) -- 15코루틴 수명 주기
코루틴에는 네 가지 상태가 있습니다. suspended(실행 중이 아님), running(현재 실행 중), dead(반환되었거나 오류가 발생함), normal(다른 코루틴을 resume했기 때문에 일시 중지됨)입니다. coroutine.status(co)로 상태를 확인하십시오.
local co = coroutine.create(function()
coroutine.yield()
end)
print(coroutine.status(co)) -- suspended
coroutine.resume(co) -- runs until yield
print(coroutine.status(co)) -- suspended again
coroutine.resume(co) -- runs until end
print(coroutine.status(co)) -- dead여러 코루틴 실행
여러 코루틴을 만들고 각 코루틴을 차례로 resume하여 실행을 교차시키십시오. 이렇게 하면 동시 실행(협력적 멀티태스킹)을 시뮬레이션할 수 있습니다. 각 코루틴은 yield 사이에 자신의 상태를 유지합니다.
local function worker(name, steps)
for i = 1, steps do
print(name .. ": step " .. i)
coroutine.yield()
end
end
local co1 = coroutine.create(function() worker("A", 3) end)
local co2 = coroutine.create(function() worker("B", 3) end)
for _ = 1, 3 do
coroutine.resume(co1)
coroutine.resume(co2)
end
-- A:1, B:1, A:2, B:2, A:3, B:3coroutine.wrap 반복
coroutine.wrap은 반복자를 만들 때 흔히 사용됩니다. 반복자가 다음 항목으로 이동할 때마다 반환된 함수를 호출합니다. 코루틴 본문이 끝나면 이 함수가 오류를 발생시키므로, 필요한 경우 pcall을 사용하거나 상태를 확인하십시오.
local function range(n)
return coroutine.wrap(function()
for i = 1, n do
coroutine.yield(i)
end
end)
end
for v in range(5) do
io.write(v .. " ")
end
print() -- 1 2 3 4 5코루틴의 오류
코루틴에서 오류가 발생하면 coroutine.resume은 false와 오류 메시지를 차례로 반환합니다. 코루틴은 dead 상태로 전환됩니다. dead 상태의 코루틴은 다시 resume할 수 없습니다.
local co = coroutine.create(function(x)
if x < 0 then error("negative input: " .. x) end
return math.sqrt(x)
end)
local ok, val = coroutine.resume(co, -1)
print(ok, val) -- false input:2: negative input: -1
print(coroutine.status(co)) -- dead
-- Can't resume a dead coroutine:
ok, val = coroutine.resume(co)
print(ok, val) -- false cannot resume dead coroutine코루틴 식별
coroutine.running()은 현재 실행 중인 코루틴과 현재 코루틴이 주 스레드인지 나타내는 불리언 값을 반환합니다. 코루틴 내부에서 이를 사용하면 자기 자신에 대한 참조를 얻을 수 있습니다.
local co = coroutine.create(function()
local self, isMain = coroutine.running()
print("type:", type(self)) -- thread
print("isMain:", isMain) -- false
print("status:", coroutine.status(self)) -- running
end)
coroutine.resume(co)
-- In main thread:
local main, isMain = coroutine.running()
print("main isMain:", isMain) -- true무한 생성기
코루틴 본문에 yield를 포함한 무한 루프를 넣을 수 있습니다. 그러면 생성기가 종료되지 않고 필요할 때 값을 생성합니다. 이는 핵심적인 사용 사례인 지연 방식의 무한 시퀀스에 해당합니다.
local function naturals(start)
return coroutine.wrap(function()
local n = start or 1
while true do
coroutine.yield(n)
n = n + 1
end
end)
end
local gen = naturals(1)
for i = 1, 8 do
io.write(gen() .. " ")
end
print() -- 1 2 3 4 5 6 7 8작업으로서의 코루틴
기본 작업 스케줄러는 코루틴을 큐에 저장하고 각 코루틴을 차례로 resume합니다. 코루틴이 yield하면 큐로 돌아갑니다. 코루틴이 종료되면 큐에서 제거합니다. 이는 최소한의 협력적 스케줄러입니다.
local tasks = {}
local function spawn(fn)
tasks[#tasks+1] = coroutine.create(fn)
end
local function run()
while #tasks > 0 do
local alive = {}
for _, co in ipairs(tasks) do
coroutine.resume(co)
if coroutine.status(co) ~= "dead" then
alive[#alive+1] = co
end
end
tasks = alive
end
end
spawn(function() for i=1,3 do print("T1:"..i); coroutine.yield() end end)
spawn(function() for i=1,3 do print("T2:"..i); coroutine.yield() end end)
run()코루틴 메모리
각 코루틴에는 고유한 스택이 있습니다. 호출이 깊게 중첩되면 스택이 크게 늘어날 수 있습니다. 고성능 환경에서는 동시에 활성 상태인 코루틴을 수천 개 생성하지 않도록 하십시오. 가능하면 코루틴을 재사용하거나 풀을 사용하십시오.
-- Coroutine pool concept
local pool = {}
local function getCoroutine(fn)
-- Reuse dead coroutine slots
for i, co in ipairs(pool) do
if coroutine.status(co) == "dead" then
pool[i] = coroutine.create(fn)
return pool[i]
end
end
local co = coroutine.create(fn)
pool[#pool+1] = co
return co
end
print("Pool pattern for coroutine reuse")빠른 확인
coroutine.create(fn) 직후 코루틴은 어떤 상태입니까?
복습: 코루틴 생성
요약:
coroutine.create(fn)→ 코루틴 객체,wrap(fn)→ 재개 가능한 함수- 상태: 일시 중단 → 실행 중 → 일시 중단/종료
coroutine.resume(co, ...)는 코루틴을 시작하거나 재개합니다- 재개 중 오류 발생: false + 오류 메시지, 코루틴은 종료 상태가 됩니다
while true do yield() end를 사용한 무한 생성기- 협력적 멀티태스킹과 지연 시퀀스에 사용합니다
자주 묻는 질문
“코루틴 만들기” 강의는 무료인가요?
네 — “코루틴 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Lua Academy 강의 전체를 잠금 해제할 수 있습니다. Lua Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“코루틴 만들기”에서 뭘 배우나요?
coroutine.create와 coroutine.wrap으로 코루틴을 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Lua Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Lua Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Lua Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“코루틴 만들기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Lua Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Lua Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.