Download

ForEachLoop behaviour with UFunction TArray return value

Hi,

maybe someone can enlighten me on this behaviour:

I have a c++ UFunction (in an UBlueprintFunctionLibrary)

UFUNCTION(BlueprintPure)
static void GetArray(TArray<int32>& result);

with the code

void UTest::GetArray(TArray<int32>& result)
{
	UE_LOG(LogTemp, Warning, TEXT("Test Output Log"));

	for (int32 i = 0; i < 10; i++)
		result.Add(i);
}

within blueprints I call this node and use the output array in a ForEachLoop to iterate the array.

The output generated is this:

LogWorld: Bringing up level for play took: 0.000377
LogTemp: Warning: Test Output Log
LogTemp: Warning: Test Output Log
LogTemp: Warning: Test Output Log
LogTemp: Warning: Test Output Log
LogTemp: Warning: Test Output Log
LogTemp: Warning: Test Output Log
LogTemp: Warning: Test Output Log
LogTemp: Warning: Test Output Log
LogTemp: Warning: Test Output Log
LogTemp: Warning: Test Output Log
LogTemp: Warning: Test Output Log

Why is the c++ UFunction called n+1 times while iterating with the ForEachLoop macro?
It seems that for the first call of the ForEachLoop node the UFunction will be called and then for each iteration again.
This does not make any sense, as I would normally asume the UFunction will be called once and the returned array will be used while inside the ForEachLoop.

Regards
Bent

Through testing it bit more, it seems that using the returned array length with a ForEachLoop
ForEachLoop
results in something similar to the following c++ code

for (int32 i = 0; i < GetArray().Num(); i++) {}

which would resolve why the UFunction is called for every iteration + 1, as the UFunction will be revaluated every iteration and the n + 1 iteration will break the loop.
That would mean I am forced to use a local blueprint array variable as cache for the returned array and use this as the array input for the ForEachLoop.

Regards
Bent