Coroutine

동시에 여러 일을 처리할 수 있도록 독립적인 흐름을 만들어요.

동시에 다른 일을 처리할 수 있도록 독립적인 흐름을 만들어 줄 수 있는 방법이에요.

일반적으로 하나의 일을 끝내고 다른 일을 할 수 있다면, Coroutine은 동시에 일을 처리할 수 있도록 해줘요.

Coroutine 함수 목록

함수명설명

coroutine.create()

coroutine 생성

coroutine.resume()

coroutine (재)실행

coroutine.yield()

coroutine 일시정지

coroutine.status()

coroutine의 상태 반환

coroutine.wrap()

함수 형태로 호출 가능한 coroutine 생성


Coroutine 사용법

coroutine.create(함수 or 익명함수)

새로운 코루틴을 생성하지만, 실행하지는 않아요.

--1. 매개변수를 사용하지 않을 경우
local co1 = coroutine.create(function()
    print("hi")
end)

--2. 매개변수를 사용할 경우
local co2 = coroutine.create(function(v)
    print(v)
end)

coroutine.resume(코루틴, 매개변수)

생성/일시정지 된 코루틴을 (재)실행 해요. 일시정지 후, 재실행을 하면 일시정지 된 부분에서부터 시작해요.

--1. 매개변수를 사용하지 않을 경우
local co1 = coroutine.create(function()
    print("hi")
end)
coroutine.resume(co1)

--2. 매개변수를 사용할 경우
local co2 = coroutine.create(function(v)
    print(v)
end)
coroutine.resume(co2, "hi")

print(coroutine.resume(코루틴))을 사용하면 코루틴의 작동 여부와 작동하지 않았을 경우 그 이유를 출력할 수 있어요.

local co1 = coroutine.create(function()
    print("hi")
end)
print(coroutine.resume(co1)) -- true
print(coroutine.status()) -- dead
print(coroutine.resume(co1)) -- false  cannot resume dead coroutine

coroutine.yield(인자) ** yield는 코루틴 내에서 사용해야해요.

실행중인 코루틴을 일시정지해요.

coroutine.yield를 인자와 함께 사용하면 print(coroutine.resume(코루틴))을 했을 때, yield가 동작한 시점에서 resume의 return값과 함께 인자가 출력돼요.

--1. 인자 없이 사용할 경우
local co1 = coroutine.create(function()
    for i = 1, 5 do
        if i == 4 then
            coroutine.yield() -- coroutine 내에서 사용해요. (i == 4일 때 정지)
        end
        print("num : "..i)
    end
end)
coroutine.resume(co1)  -- 1 ~ 3까지 출력
print("재시작")        -- 재시작
coroutine.resume(co1)  -- 4 ~ 5 출력 (일시정지한 i == 4부터 다시 시작)

--2. 인자와 함께 사용할 경우
local co1 = coroutine.create(function()
    for i = 1, 5 do
        if i == 4 then
            coroutine.yield("정지") -- coroutine 내에서 사용해요. (i == 4일 때 정지)
        end
        print("num : "..i)
    end
end)
print(coroutine.resume(co1))  -- 1 ~ 3까지 출력 후 'true 정지' 출력
print("재시작")        -- 재시작
coroutine.resume(co1)  -- 4 ~ 5 출력 (일시정지한 i == 4부터 다시 시작)

coroutine.status(코루틴)

코루틴 상태를 반환해요. 코루틴의 상태는 running (실행 중) / suspend (정지) / dead (종료) 가 있어요.

local co = coroutine.create(function()
    for i = 1, 5 do
        if i == 4 then
            coroutine.yield() -- coroutine 내에서 사용해요.
        end
        print("num : "..i)
    end
end)
coroutine.resume(co)         -- 1 ~ 3까지 출력
print(coroutine.status(co))  -- suspend

print("재시작")               -- 재시작

coroutine.resume(co)         -- 4 ~ 5 출력
print(coroutine.status(co))  -- dead

coroutine.wrap(함수 or 익명함수)

함수로 이용가능한 코루틴 생성해요. wrap을 사용하면 yield로 정지 후 resume을 사용하지 않고 재시작할 수 있어요.

-- wrap을 사용하면 yield로 정지 후 재시작할 때 resume을 사용할 필요가 없어요.

local co = coroutine.wrap(function()
    for i = 1, 5 do
        print("num : "..i)
        coroutine.yield() -- coroutine 내에서 사용해요.
    end
end)
co() -- num : 1
co() -- num : 2
co() -- num : 3
co() -- num : 4
co() -- num : 5

Last updated