Sleeper is a simple module that makes it easy to pause and resume your code using coroutines.
It’s perfect for situations where you want to avoid using while or repeat loops to check for conditions, and it’s useful for managing multiple coroutines.
Features
Sleeper.New() — creates a new Sleeper object
SleeperObject:Sleep(Index: any?, Timeout: number?, ...: any) — pauses the current coroutine, optionally storing it under a custom index
SleeperObject:OnSleep(Index: any, Function: (any) -> (any)) — Fires the function when the index is paused
SleeperObject:OnWakingUp(Index: any, Function: (any) -> (any)) — Fires the function when the index is resumed
SleeperObject:IsSleeping(Index: any) — Returns if the index is paused
SleeperObject:GetSleepDuration(Index: any) — Gets how long the given index has been asleep
SleeperObject:WakeUpByIndex(index, ...) — resumes the coroutine that was paused using the given index
SleeperObject:WakeUpByPosition(position, ...) — resumes the coroutine based on the order it was added
SleeperObject:WakeUpAll(...) — resumes all paused coroutines
SleeperObject:Destroy() — cleans up the object
Examples
Example #1: Wait for Condition
local Sleeper = require(...)
local SleeperObject = Sleeper.New()
local condition = false
task.delay(3, function()
condition = true
SleeperObject:WakeUpByIndex("Condition")
end)
SleeperObject:Sleep("Condition")
print(condition) -- true
This replaces code like:
while not condition do task.wait() end
Example #2: Simple Module Loader
local Sleeper = require(...)
local sleepers = {}
local loadedModules = {}
local ModuleLoader = {}
function ModuleLoader.Get(name)
if not loadedModules[name] then
sleepers[name] = sleepers[name] or Sleeper.New()
sleepers[name]:Sleep()
end
return loadedModules[name]
end
function ModuleLoader.Init(modules)
for _, moduleScript in ipairs(modules) do
local name = moduleScript.Name
loadedModules[name] = require(moduleScript)
if sleepers[name] then
sleepers[name]:WakeUpAll()
sleepers[name]:Destroy()
sleepers[name] = nil
end
end
end
return ModuleLoader
Other Use Cases
- Queue systems
What's New
- 4 new METHODS (Yeah, I know it’s not much)
- Sleeping with a timeout
- I forgot
You can use this module for many other things beyond just these examples. It’s flexible and can be adapted to different situations where you need to manage coroutines.
(Totally forgot about this module, but it’s updated now!)
- Yes🥰
- No😈