Tutorial Chapter 7: Array Display |
The main module, cust_stub.4gl calls the library function display_custarr, which uses a cursor with a FOREACH statement to load rows from the customer table into a program array. The DISPLAY ARRAY statement displays the records in the program array to the screen array defined in the form specification file.
A program array is an ordered set of elements all of the same data type. You can create one-, two-, or three-dimensional arrays. The elements of the array can be simple types or they can be records.
Arrays can be:
static - defined with an explicit size for all dimensions.
dynamic - has a variable size. Dynamic arrays have no theoretical size limit.
All elements of static arrays are initialized even if the array is not used. Therefore, defining huge static arrays may use a lot of memory. The elements of dynamic arrays are allocated automatically by the runtime system, as needed.
Example of a dynamic array of records definition:
01 DEFINE cust_arr DYNAMIC ARRAY OF RECORD 02 store_num LIKE customer.store_num, 03 city LIKE customer.city 04 END RECORD
This array variable is named cust_arr; each element of the array contains the members store_num and city. The size of the array will be determined by the runtime system, based on the program logic that is written to fill the array. The first element of any array is indexed with subscript 1. You would access the store_num member of the 10th element of the array by writing cust_arr[10].store_num.
The FOREACH statement is equivalent to using the OPEN, FETCH and CLOSE statements to retrieve and process all the rows selected by a query, and is especially useful when loading arrays.
01 DECLARE custlist_curs CURSOR FOR 02 SELECT store_num, city FROM customer 03 CALL cust_arr.clear() 04 FOREACH custlist_curs INTO cust_rec.* 05 CALL cust_arr.appendElement() 06 LET cust_arr[cust_arr.getLength()].* = cust_rec.* 07 END FOREACH
The FOREACH statement shown: