Arrays
An array is a data structure in which many values are associated with the same variable name, but each value has its own 'subscript' or 'index value' to distinguish it from the others. For example, a series of names could be stored in variables name_1, name_2, name_3, and so forth. In this case we could say that the names are stored in an array called names. Data stored in this way is much easier for a program to manage than data stored in completely unrelated variable names.
Miva Script does not have built-in support for arrays, but it is easy to simulate arrays by using macros. The array subscripts can be generated by a value referred to by a macro.
Here is an example that reads a list of values from a data file and stores each one in a different element of an array:
- <MvASSIGN name="counter" value="1">
- <MvIMPORT
- FILE="workers.dat"
- FIELDS="worker,amount"
- DELIMITER="|">
- <MvASSIGN name="person_&[counter];" value="{worker}">
- <MvASSIGN name="salary_&[counter];" value="{amount}">
- <MvASSIGN name="counter" value="{counter+1}">
- </MvIMPORT>
This example actually uses two arrays, one whose variables start with person_, and another whose variables start with salary_. When a line of data is read from the data file, values are stored in the variables worker and amount. The first time a line of data is read, the value of the variable counter is 1.
Since macros are evaluated before a line of code is executed, the first two <MvASSIGN> tags after the <MvIMPORT> effectively become:
- <MvASSIGN name="person_1" value="{worker}">
- <MvASSIGN name="salary_1" value="{amount}">
Then the variables person_1 and salary_1 are assigned the current values of worker and amount, respectively. Next, the value of counter is increased by one. Therefore, the next time through the loop, the variables person_2 and salary_2 are created and assigned values. When all of the data has been read in, two series of variables person_1, person_2,...,person_N and salary_1, salary_2,...,salary_N have been created and assigned values.
One advantage of storing data in this way is that elsewhere in the program it would be very easy to implement a loop that reads through the entire array; another is that if you know the array subscript associated with a particular person, it is easy to access both the name and salary values for that person.