# Coroutine

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

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

![](/files/xOhh21bz1Glx4Zf3qQiI)

## Coroutine 함수 목록

<table><thead><tr><th width="239.061401259606">함수명</th><th>설명</th></tr></thead><tbody><tr><td>coroutine.create()</td><td>coroutine 생성</td></tr><tr><td>coroutine.resume()</td><td>coroutine (재)실행</td></tr><tr><td>coroutine.yield()</td><td>coroutine 일시정지</td></tr><tr><td>coroutine.status()</td><td>coroutine의 상태 반환</td></tr><tr><td>coroutine.wrap()</td><td>함수 형태로 호출 가능한 coroutine 생성</td></tr></tbody></table>

***

## Coroutine 사용법

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

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

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

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

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

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

```lua
--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(코루틴))을 사용하면 코루틴의 작동 여부와 작동하지 않았을 경우 \
그 이유를 출력할 수 있어요.

```lua
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는 코루틴 내에서 사용해야해요.

실행중인 코루틴을 일시정지해요.&#x20;

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

```lua
--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 (종료) 가 있어요.

```lua
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을 사용하지 않고 재시작할 수 있어요.

```lua
-- 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
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ditoland-utplus.gitbook.io/ditoland/manual/coroutine.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
