Last active
October 14, 2021 15:32
-
-
Save lucasmz-dev/99099b812846ecd60d5421e8036f8cab to your computer and use it in GitHub Desktop.
Yielder (nicer way to do custom resuming)
This file contains 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
local Yielder = {} | |
Yielder.__index = Yielder | |
function Yielder.new(): Class | |
return setmetatable({ | |
_thread = nil | |
}, Yielder) | |
end | |
function Yielder:Yield(...): (...any) | |
if self._thread ~= nil then | |
error("Cannot yield two threads at once", 2) | |
end | |
self._thread = coroutine.running() | |
return coroutine.yield(...) | |
end | |
function Yielder:Resume(...): (...any) | |
if self._thread == nil then | |
error("No thread to resume", 2) | |
end | |
local thread = self._thread | |
self._thread = nil | |
return task.spawn(thread, ...) | |
end | |
export type Class = typeof( | |
setmetatable({}, Yielder) | |
) | |
return Yielder |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment