Last active
December 21, 2015 21:09
-
-
Save qiuyuzhou/6366160 to your computer and use it in GitHub Desktop.
Wrap and patch lua coroutine module in order to add coroutine.kill which is similar to g.throw in python greenlet.
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
module('greenlet',package.seeall) | |
local _resume = coroutine.resume | |
local _yield = coroutine.yield | |
local _create = coroutine.create | |
local _wrap = coroutine.wrap | |
function create(func) | |
function f(is_kill,...) | |
return func(...) | |
end | |
return _create(f) | |
end | |
function yield(...) | |
function f(is_kill,...) | |
if is_kill then | |
error('killed') | |
end | |
return ... | |
end | |
return f( _yield(...) ) | |
end | |
function resume( co, ... ) | |
return _resume( co, false, ... ) | |
end | |
function kill( co ) | |
_resume( co, true ) | |
end | |
function wrap(f) | |
local co = create(f) | |
local function wrap_f(...) | |
local function _remove_first_return_value(iOk,...) | |
if iOk then | |
return ... | |
else | |
error(...) | |
end | |
end | |
return _remove_first_return_value( resume(co, ...) ) | |
end | |
return wrap_f | |
end | |
function patch() | |
if coroutine._patched_by_greenlet ~= true then | |
coroutine.create = create | |
coroutine.resume = resume | |
coroutine.yield = yield | |
coroutine.kill = kill | |
coroutine.wrap = wrap | |
coroutine._patched_by_greenlet = true | |
end | |
end | |
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
require('greenlet') | |
greenlet.patch() | |
function foo() | |
print(1) | |
coroutine.yield() | |
print(2) | |
coroutine.yield() | |
print(3) | |
end | |
co = coroutine.create(foo) | |
coroutine.resume( co ) | |
print( coroutine.status( co ) ) | |
coroutine.resume( co ) | |
print( coroutine.status( co ) ) | |
coroutine.kill( co ) | |
print( coroutine.status( co ) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment