Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved compatibility with old coroutines #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions src/coroutine/make.lua
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,24 @@ local status = coroutine.status
local wrap = coroutine.wrap
local yield = coroutine.yield

return function (tag)
local depth = 1
local maxdepth = math.huge -- Change this to change max coroutine depth --

local function prep(f) -- Prepare function environment --
if getfenv and setfenv and setmetatable then
local tbo = getfenv(f)
local tba = setmetatable({coroutine = coronest()},{__index = tbo, __newindex = tbo})
setfenv(f,tba)
elseif debug and debug.getupvalue and debug.setupvalue and setmetatable then
local tbo = debug.getupvalue(f,1)
local tba = setmetatable({coroutine = coronest()},{__index = tbo, __newindex = tbo})
debug.setupvalue(f,1,tba)
end
return f
end

local coronest
coronest = function (tag)
local coroutine = {
isyieldable = isyieldable,
running = running,
Expand All @@ -33,17 +50,23 @@ return function (tag)
end
end

function coroutine.create (f)
function coroutine.create (fa)
local f = prep(fa)
return create (function (...)
return tag, f (...)
end)
end

function coroutine.resume (co, ...)
if depth >= maxdepth then
return false, "Maximum coroutine depth ".. maxdepth .." reached!"
end
depth = depth + 1
return for_resume (co, resume (co, ...))
end

function coroutine.wrap (f)
function coroutine.wrap (fa)
local f = prep(fa)
local co = wrap (function (...)
return tag, f (...)
end)
Expand All @@ -53,8 +76,10 @@ return function (tag)
end

function coroutine.yield (...)
depth = depth - 1
return yield (tag, ...)
end

return coroutine
end
return coronest