Functions

AEval

Execute a code block for each element in an array

Syntax

Signature
ITEM *AEval( ITEM *array, AEvalBlock block, int start, int count, void *cargo );

Arguments

array Array to traverse.

block Function called for each element: void block( ITEM *element, int index, void *cargo ).

start First position, counted from 1. NIL or a value below 1 starts at 1.

count Number of elements to process. NIL processes through the end of the array.

cargo Any pointer, passed unchanged to each call of the block. It takes the place of variables outside the block; NULL when not needed.

Return value

The array, or NULL if array is not an array or block is NULL.

Description

Process a range of elements in order with a C callback. The callback receives a temporary copy of each item, its one-based position and the `cargo` pointer. Its result is ignored. For example, the callback can accumulate a total in application data held by `cargo`.

Assigning a different value to the temporary item affects only the copy. To replace an array element, pass the array through `cargo` and update it by position. A copied subarray still refers to the same nested array, so edits inside that subarray are visible to the caller.

The loop checks the array's current length after each callback and stops if the next position is beyond it. The original upper bound of the requested range still applies.

Example

aeval.c
#include "xdev-wtui.h"

#include <stdio.h>

static void addPrice( ITEM *element, int index, void *cargo )
{
   double *total = cargo;

   printf( "%d: %.2f\n", index, ItemGetND( element ) );
   *total += ItemGetND( element );
}

int main( void )
{
   ITEM  *prices = Array( 3 );
   double total = 0;

   if( !prices )
      return 1;

   ArraySetND( prices, 1, 2.50 );
   ArraySetND( prices, 2, 4.00 );
   ArraySetND( prices, 3, 1.25 );

   AEval( prices, addPrice, NIL, NIL, &total );
   printf( "Total: %.2f\n", total );

   ItemRelease( prices );

   return 0;
}

Output

1: 2.50
2: 4.00
3: 1.25
Total: 7.75

See also