Created
August 14, 2014 07:57
-
-
Save chunpu/5413b046031d8a920fa5 to your computer and use it in GitHub Desktop.
a koa style lua sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- koa style downstream and upstream | |
local thread1 = coroutine.create(function(down) | |
print('thread1-down') | |
coroutine.yield(down) | |
print('thread1-up') | |
end) | |
local thread2 = coroutine.create(function(down) | |
print('thread2-down') | |
coroutine.yield(down) | |
print('thread2-up') | |
end) | |
local arr = { | |
thread1, | |
function(down) | |
print(1) | |
down() | |
end, | |
thread2, | |
function(down) | |
print(2) | |
down() | |
end, | |
} | |
co(arr)() | |
--[[ output >> | |
thread1-down | |
1 | |
thread2-down | |
2 | |
thread2-up | |
thread1-up | |
]] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- koa style downstream and upstream | |
function co(arr) | |
local i = 0 | |
local len = #arr | |
return function() | |
function down(ok) | |
if len <= i then return end | |
i = i + 1 | |
local x = arr[i] | |
local tp = type(x) | |
if tp == 'function' then | |
x(down) | |
elseif tp == 'thread' then | |
local chain, ret = coroutine.resume(x, down) | |
if chain and ret == down then | |
down() | |
coroutine.resume(x, down) | |
end | |
end | |
end | |
down() | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment