I want to use ‘sync’ to call an asynchronous function to act on objects in an array, but I don’t know in advance which will need to be acted upon. The following code compiles, but the functions in the for loops execute one after the other. Does someone know how to write this so that the functions all execute at the same time?
sync:
for (i = 1…3):
for (j = 1…3):
if (Test(i, j) = true):
CallAsyncFunction(i, j)
OtherFunction()
You’re not understanding how the sync statement works, it doesn’t let you call an asynchronous function but rather wait for multiple asynchronous/suspending blocks to end before completing
The issue with this method is that it’s not implemented natively for arrays rn
For some reason you didn’t put any indent here, so I’ll assume you’re trying to do the following (which shouldn’t compile, just pseudo code)
sync:
for (i = 1…3):
for (j = 1…3):
if (Test(i, j) = true):
CallAsyncFunction(i, j) # Wait for all async calls to complete before calling the OtherFunction()
OtherFunction()
It’s not pretty but you could try something like that
OnBegin<override>()<suspends>:void=
Tasks := for(I := 1..10) { spawn{CallAsyncFunction()} }
# Will fail if the async method completes instantly though
AwaitFunctions(Tasks)
OtherFunction()
CallAsyncFunction()<suspends>:void=
Sleep(GetRandomFloat(0.1, 5.0))
Print("CALL ASYNC FUNCTION")
AwaitFunctions(Functions: []awaitable(t) where t:type)<suspends>:void=
CompleteEvent : event() = event(){}
var CompletedCount : int = 0
sync:
loop:
CompleteEvent.Await()
set CompletedCount += 1
if(CompletedCount >= Functions.Length):
break
for(Function : Functions):
spawn{AwaitFunction(Function, CompleteEvent)}
Sleep(-1.0) # Tell the compiler that we're suspending eventhough we're not
AwaitFunction(Function: awaitable(t), CompleteEvent: event() where t:type)<suspends>:void=
Function.Await()
CompleteEvent.Signal()
OtherFunction():void=
Print("OTHER FUNCTION")