wolfhacklua API 1.1 Forum

task

Coroutines the host resumes for you: wait, spread work over frames, and wait for a download or a texture without callbacks.

since 1.0no permission needed

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): integer

Starts fn as a task. It runs until its first pause immediately.

ParameterTypeDescription
fnfunctionThe task body.
...anyArguments passed to fn.
ReturnsDescription
integerA task id.
lua
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.

ParameterTypeDescription
secondsnumberHow 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.

ParameterTypeDescription
frames optionalintegerFrames to skip. default 1

task.await#since 1.0

task.await(handle: Request | Texture | ScanHandle): table | nil

Pauses the running task until the handle is done. Only inside a task.

ParameterTypeDescription
handleRequest | Texture | ScanHandleA net request, a texture or a memory scan.
ReturnsDescription
table | nilA request gives its response table; a texture gives its size; a scan gives the address (or nil). A cancelled handle gives nil.
lua
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): boolean

Stops a task.

ParameterTypeDescription
idintegerA task id.
ReturnsDescription
booleantrue when a task was cancelled.

task.count#since 1.0

task.count(): integer

How many tasks this script has running.

ReturnsDescription
integerThe number of live tasks.
API 1.1 · source docs-src/api/task.json