Function
async
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
awaitWaits for a result inside anasynctask. It takes two forms. The first is a starter function: it receivesresumeand starts something that ends in a callback (adbQueryquery,fetchRemote, a timer). When the callback callsresume(...),awaitreturns the same values. The second form is another task fromasync:awaitwaits until it ends and returns its results, and if that task failed, it re-throws the error (catch it withpcall).sleepPauses anasynctask for the given time. Meanwhile other scripts, the server and the game run normally.sleep(0)waits until the next server frame (the same assetTimerwith interval 0).waitForEventPauses anasynctask until an event happens. Returns the event'ssourceelement and its arguments. With a time limit it returnsfalseif the event did not happen in time. The handler and the limit timer are removed when the wait ends.getTaskStatusReturns the state of a task fromasync:"running"(waiting or working),"done"(finished) or"failed"(error). After the state it returns the values returned by the task function or, for"failed", the error message.isTaskChecks whether a value is a task returned byasync.