diff --git a/src/coroutine/make.lua b/src/coroutine/make.lua index 15e3c98..eb3f28e 100644 --- a/src/coroutine/make.lua +++ b/src/coroutine/make.lua @@ -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, @@ -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) @@ -53,8 +76,10 @@ return function (tag) end function coroutine.yield (...) + depth = depth - 1 return yield (tag, ...) end return coroutine end +return coronest