task
Coroutines the host resumes for you: wait, spread work over frames, and wait for a download or a texture without callbacks.
task.spawn starts a function as a coroutine. Inside it, task.wait, task.yield and task.await pause it and give the frame back; the host resumes it later. At most 32 tasks per script. Outside a task these functions raise an error. Tasks are cancelled when the script stops.
Use task.yield() to split heavy work: a loop that handles 200 items per frame instead of 20 000 in one go stays inside the time budget.
Reference#
task.spawn#since 1.0
task.spawn(fn: function, ...: any): integerStarts fn as a task. It runs until its first pause immediately.
| Parameter | Type | Description |
|---|---|---|
fn | function | The task body. |
... | any | Arguments passed to fn. |
| Returns | Description |
|---|---|
integer | A task id. |
task.spawn(function()
log.info("start")
task.wait(2)
log.info("two seconds later")
end)task.wait#since 1.0
task.wait(seconds: number)Pauses the running task for that many seconds of script time. Only inside a task.
| Parameter | Type | Description |
|---|---|---|
seconds | number | How long to pause. |
task.yield#since 1.0
task.yield(frames?: integer)Pauses the running task for that many frames (1 to 100000). Only inside a task.
| Parameter | Type | Description |
|---|---|---|
frames optional | integer | Frames to skip. default 1 |
task.await#since 1.0
task.await(handle: Request | Texture | ScanHandle): table | nilPauses the running task until the handle is done. Only inside a task.
| Parameter | Type | Description |
|---|---|---|
handle | Request | Texture | ScanHandle | A net request, a texture or a memory scan. |
| Returns | Description |
|---|---|
table | nil | A request gives its response table; a texture gives its size; a scan gives the address (or nil). A cancelled handle gives nil. |
task.spawn(function()
local res = task.await(net.get("https://api.example.com/x"))
if res and res.ok then log.info(res.status) end
end)task.cancel#since 1.0
task.cancel(id: integer): booleanStops a task.
| Parameter | Type | Description |
|---|---|---|
id | integer | A task id. |
| Returns | Description |
|---|---|
boolean | true when a task was cancelled. |
task.count#since 1.0
task.count(): integerHow many tasks this script has running.
| Returns | Description |
|---|---|
integer | The number of live tasks. |