ServersYour serverFor creatorsForumFAQDocumentationSecurity
Download the launcher
  1. Documentation
  2. Shared functions
  3. async

Function

async

Server and clientTimersTrilogy Hub only

Runs a function as a task (coroutine). The code in the task runs immediately until its first wait (sleep, await, waitForEvent). Then it yields and the server and the game keep running. When the wait is over, the task continues from where it stopped. This lets you write steps spread over time (a countdown, a database query, an HTTP response, waiting for a player) one after another, without nested callbacks and timers.

Syntax

task async(function fn [, var ...])

Arguments

fnfunction
The task function.
...var, optional = nil
Arguments passed to the function.

Returns

The task (check it with getTaskStatus), or false on a bad argument.

Example

addCommandHandler("odliczanie", function(player)
    async(function()
        for i = 3, 1, -1 do
            outputChatBox(i .. "...", player)
            sleep(1000)
        end
        outputChatBox("Start!", player)
    end)
end)

Notes

A task belongs to its resource. The timers and handlers a task waits on belong to the resource that started it, so stopping the resource also ends its waiting tasks.

An error in a task does not crash the script. It goes to the console as async: ... and the task gets the failed state. Code that does not yield for 5 seconds is aborted (infinite loop protection). On the client, time a function spends waiting for the game (e.g. under the loading screen when joining) does not count.

See also