Iterates over async iterator, calling it with given arguments.
Example
lua
---@async---@return AsyncIterator<number>localfunctioncount( from, to )
for i = from, to do
futures.yield( i )
endendlocalfunctionmain()
for i in futures.apairs( count, 1, 5 ) doprint( i ) -- 1, 2, 3, 4, 5endend
futures.run( main )
Parameters
Name
Type
Description
iterator
async
fun(...): futures.AsyncIterator<K, V> The async iterator function to drive.
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
---@asynclocalfunctionwork()
whiletruedoprint( "working" )
sleep( 1 )
endendlocal 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`endend )
futures.cancel( co ) -- this will stop coroutine from executing
Puts current coroutine to sleep until futures.wakeup is called can be used to wait for some event.
Example
lua
---@asynclocalfunctionrequest( 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.wakeupendlocalfunctionmain()
local body = request( "https://example.com" )
print( body ) -- <!DOCTYPE html>...end
futures.run( main )
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
---@asynclocalfunctionasyncFunction( a, b )
sleep( 1 )
returnend
futures.run( asyncFunction, function( ok, result )
if ok thenprint( "result:", result ) -- result: 4elseprint( "error:", result )
endend, 2, 2 ) -- 2 and 2 are arguments for asyncFunction
Parameters
Name
Type
Description
target
async
fun(...):... The function to execute.
callbackoptional
fun(ok: boolean, ...)?
The callback function.
...
any
Arguments to pass into the target function
Returns
Type
Name
Description
thread
co
The created coroutine object.
See also
futures.cancel you can cancel returned coroutine from this function