Petrichor.Async#
require("Petrichor.Async") provides coroutine-based async/await utilities for Luau scripts. It enables writing sequential code that yields for timers or scheduler defers without blocking the main game thread.
Loading the module#
API#
| Function | Returns | Description |
|---|---|---|
Async.async(func) | function | Wraps func in an asynchronous execution context (coroutine step driver). Calling the returned function starts execution. |
Async.await(thunk) | any | Yields execution until thunk(step) completes and passes its result back. |
Async.defer() | thunk | Yields execution to defer the remainder of the async function to the next engine scheduler step. |
Async.delay(seconds) | thunk | Returns a thunk that waits for seconds wall-clock time before resuming. |
Async.sleep(seconds) | any | Convenience helper that awaits Async.delay(seconds). |
Example#
local Async = require("Petrichor.Async")
local Log = require("Petrichor.Log")
local myTask = Async.async(function()
Log.info("my-mod", "Starting async sequence...")
-- Sleep for 2.5 seconds without blocking game tick
Async.sleep(2.5)
Log.info("my-mod", "Resumed after 2.5s delay!")
-- Defer execution to next scheduler loop
Async.await(Async.defer())
Log.info("my-mod", "Deferred step complete.")
end)
myTask()
import * as Async from "Petrichor.Async"
import * as Log from "Petrichor.Log"
const myTask = Async.async(() => {
Log.info("my-mod", "Starting async sequence...")
Async.sleep(2.5)
Log.info("my-mod", "Resumed after 2.5s delay!")
Async.await(Async.defer())
Log.info("my-mod", "Deferred step complete.")
})
myTask()
See also#
- Petrichor.Task: Promise-based async task driver
- Petrichor.Timer: Wall-clock timers