0%

Lua coroutine

API

1
2
3
4
5
6
7
8
9
10
11
12
13
-- create function,It returns a value of type thread, which represents the new coroutine
co = coroutine.create(funtion
print("hi")
end)

-- check the state of a coroutine
coroutine.status(co)

-- starts the execution of a coroutine
coroutine.resume(co)

-- The real power of coroutines stems from the yield function, which allows a running coroutine to suspend its execution so that it can be resumed later
coroutine.yield()

Status

  • suspend
  • running
  • normal
  • dead

Status Switching

1
2
3
4
5
6
7
8
9
10
11
(create)
|
|
v caller resume the coroutime resume other coroutine
suspend -------------------------------> running --------------------------------> normal
<------------------------------ | <-------------------------------
yield |return other coroutine yield/return
(return controll to caller) |
v
dead
(return controll to caller)

note

Note that resume runs in protected mode. Therefore, if there is any error inside a coroutine, Lua will not show the error message, but instead will return it to the resume call.

A useful facility in Lua is that a pair resume-yield can exchange data between them. The first resume, which has no corresponding yield waiting for it, passes its extra arguments as arguments to the coroutine main function

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function status()
print("co1's status :"..coroutine.status(co1).." ,co2's status: "..coroutine.status(co2))
end

co1 = coroutine.create(function ( a )
print("arg is :"..a)
status()

local stat, rere = coroutine.resume(co2,"2")
print("resume's return is "..rere)
status()

local stat2,rere2 = coroutine.resume(co2,"4")
print("resume's return is "..rere2)

local arg = coroutine.yield("6")
end)

co2 = coroutine.create(function ( a )
print("arg is :"..a)
status()

local rey = coroutine.yield("3")
print("yeild's return is " .. rey)
status()

coroutine.yield("5")
end)

stat,mainre = coroutine.resume(co1,"1")
status()
print("last return is "..mainre)

output

1
2
3
4
5
6
7
8
9
10
11
arg  1
co1's status :running ,co2's status: suspended
arg is :2
co1's status :normal ,co2's status: running
resume's return is 3
co1's status :running ,co2's status: suspended
yeild's return is 4
co1's status :normal ,co2's status: running
resume's return is 5
co1's status :suspended ,co2's status: suspended
last return is 6

Reference & Thanks