dreamworkAPI
Ctrl K
GitHub
libraryDocs / futures

futures

librarysharedmenusource

This library provides Python-like futures for asynchronous programming, such as Futures, Tasks, Channels, and async iterators.

Author: Retr0

Classes & types

Functions

futures.allAwaits all given awaitables (in order) and returns their results in a table.
futures.anextRetrieves the next value from an async iterator coroutine.
futures.anyReturns first result of futures, or error.
futures.apairsIterates over async iterator, calling it with given arguments.
futures.cancelCancels execution of passed coroutine.
futures.collectCollects all values from async iterator into a list.
futures.collectTableCollects all values from async iterator into a table.
futures.isCancelChecks whether the value is the cancellation signal thrown by futures.cancel.
futures.pendingPuts current coroutine to sleep until futures.wakeup is called can be used to wait for some event.
futures.runExecutes a function in a new coroutine you can use this function to call async functions even in sync code callback wil…
futures.sleepPuts current thread to sleep for given amount of seconds.
futures.transferTransfers data between coroutines in symmetrical way used in asynchronous iterators you probably should not use it.
futures.wakeupUsed to wake up a pending coroutine.
futures.yieldYields given arguments to the apairs listener.

#futures.all

sharedmenuasyncsource
async function futures.all(awaitables: Awaitable[]): any[]

Awaits all given awaitables (in order) and returns their results in a table.

Each item must implement :await() (e.g. Future/Task) — plain functions are not supported.

If any awaitable throws, the error is re-thrown and all remaining awaitables are cancelled.

Parameters
NameTypeDescription
awaitablesAwaitable[]The list of awaitables (e.g. Future/Task instances) to await.
Returns
TypeNameDescription
any[]

#futures.anext

sharedmenuasyncnodiscardsource
async function futures.anext(iterator: thread, ...: any): any

Retrieves the next value from an async iterator coroutine.

Returned by futures.apairs; you probably shouldn't call it directly.

Parameters
NameTypeDescription
iteratorthreadThe async-iterator coroutine, as returned by futures.apairs.
...anyValues to resume the iterator with.
Returns
TypeNameDescription
any...The next yielded value(s), or nothing if the iterator finished.
See also

#futures.any

sharedmenuasyncsource
async function futures.any(futureList: Future[]): any

Returns first result of futures, or error.

Other awaitables will be cancelled after first result or error.

Parameters
NameTypeDescription
futureListFuture[]The list of futures to race against each other.
Returns
TypeNameDescription
any

#futures.apairs

sharedmenuasyncnodiscardsource
async function futures.apairs(iterator: async, ...: any): async, thread

Iterates over async iterator, calling it with given arguments.

Example

lua
---@async
---@return AsyncIterator<number>
local function count( from, to )
    for i = from, to do
        futures.yield( i )
    end
end

local function main()
    for i in futures.apairs( count, 1, 5 ) do
        print( i ) -- 1, 2, 3, 4, 5
    end
end

futures.run( main )
Parameters
NameTypeDescription
iteratorasyncfun(...): futures.AsyncIterator<K, V> The async iterator function to drive.
...anyArguments to pass to iterator.
Returns
TypeNameDescription
asyncfun(...): K, V
thread
See also

#futures.cancel

sharedmenusource
function futures.cancel(co: thread)

Cancels execution of passed coroutine.

ACTION_CANCEL will be thrown in coroutine.

NB! pcall inside coroutine can catch this error so coroutine may not be cancelled because of pcall, use futures.isCancel to detect it and rethrow.

Example

lua
---@async
local function work()
    while true do
       print( "working" )
       sleep( 1 )
    end
end

local co = futures.run( work, function( ok, value )
    if futures.isCancel( value ) then
        -- because we cancelled coroutine
        -- ok will be false
        -- value will be `ACTION_CANCEL`
    end
end )

futures.cancel( co ) -- this will stop coroutine from executing
Parameters
NameTypeDescription
cothreadThe coroutine to cancel.

#futures.collect

sharedmenuasyncnodiscardsource
async function futures.collect(iterator: async, ...: any): V[], number

Collects all values from async iterator into a list.

Parameters
NameTypeDescription
iteratorasyncfun(...): futures.AsyncIterator<V> The async iterator to collect values from.
...anyArguments to pass to iterator.
Returns
TypeNameDescription
V[]results
numberlength

#futures.collectTable

sharedmenuasyncnodiscardsource
async function futures.collectTable(iterator: async, ...: any): table<K, V>

Collects all values from async iterator into a table.

Parameters
NameTypeDescription
iteratorasyncfun(...): futures.AsyncIterator<K, V> The async iterator to collect entries from.
...anyArguments to pass to iterator.
Returns
TypeNameDescription
table<K, V>result

#futures.isCancel

sharedmenunodiscardsource
function futures.isCancel(value: any): boolean

Checks whether the value is the cancellation signal thrown by futures.cancel.

Parameters
NameTypeDescription
valueanyThe value to check, e.g. an error caught by pcall or the value of a futures.run callback.
Returns
TypeNameDescription
booleanis_canceltrue if the value is the cancellation signal, otherwise false.

#futures.pending

sharedmenuasyncsource
async function futures.pending(): ...

Puts current coroutine to sleep until futures.wakeup is called can be used to wait for some event.

Example

lua
---@async
local function request( url )
    local co = futures.running()

    http.Fetch( url, function( body, size, headers, code )
        futures.wakeup( co, body )
    end)

    return futures.pending() -- this will return all arguments passed to futures.wakeup
end

local function main()
    local body = request( "https://example.com" )
    print( body ) -- <!DOCTYPE html>...
end

futures.run( main )
Returns
TypeNameDescription
...
See also

#futures.run

sharedmenusource
function futures.run(target: async, callback?: fun(ok: boolean, ...)?, ...: any): thread

Executes a function in a new coroutine you can use this function to call async functions even in sync code callback will be called when function returned or errored it will be called with these arguments:

  • ok: boolean - whether the function returned without errors
  • ... - return values of the function (or error message)

Example

lua
---@async
local function asyncFunction( a, b )
    sleep( 1 )
    return
end

futures.run( asyncFunction, function( ok, result )
    if ok then
        print( "result:", result ) -- result: 4
    else
        print( "error:", result )
    end
end, 2, 2 ) -- 2 and 2 are arguments for asyncFunction
Parameters
NameTypeDescription
targetasyncfun(...):... The function to execute.
callbackoptionalfun(ok: boolean, ...)?The callback function.
...anyArguments to pass into the target function
Returns
TypeNameDescription
threadcoThe created coroutine object.
See also

#futures.sleep

sharedmenuasyncsource
async function futures.sleep(seconds: number)

Puts current thread to sleep for given amount of seconds.

Parameters
NameTypeDescription
secondsnumberHow long to sleep, in seconds.
See also

#futures.transfer

sharedmenuasyncsource
async function futures.transfer(co: thread, ...: any): boolean, any

Transfers data between coroutines in symmetrical way used in asynchronous iterators you probably should not use it.

Parameters
NameTypeDescription
cothreadThe coroutine to transfer control and values to.
...anyValues to pass to co.
Returns
TypeNameDescription
booleansuccess
any...
See also

#futures.wakeup

sharedmenusource
function futures.wakeup(co: thread, ...: any)

Used to wake up a pending coroutine.

Parameters
NameTypeDescription
cothreadThe coroutine currently suspended inside futures.pending.
...anyValues to return from that futures.pending() call.
See also

#futures.yield

sharedmenuasyncsource
async function futures.yield(...: any): ...

Yields given arguments to the apairs listener.

Parameters
NameTypeDescription
...anyValues to yield to the listener.
Returns
TypeNameDescription
...anyValues passed back to this coroutine via ACTION_RESUME.
See also
Generated from the dreamwork meta branch.