Advanced Structure Usage

Facilities exist to process structures in a general way using tag numbers rather than tag names. A tag can be referenced using its index, enclosed in parentheses, as follows:

Variable_Name.(Tag_Index)... ... ...

The Tag_Index ranges from zero to the number of fields minus one.

Note
The Tag_Index is an expression, the result of which is taken to be a tag position. In order for the IDL parser to understand that this is the case, you must enclose the Tag_Index in parentheses. This is not an array indexing operation, so the use of square brackets ([]) is not allowed in this context.

Number of Structure Tags

The function N_TAGS(Structure) returns the number of fields in a structure. To obtain the size, in bytes, of a structure call N_TAGS with the /LENGTH keyword.

Names of Structure Tags

The function TAG_NAMES(Structure) returns a string array containing the names of each tag. To return the name of the structure itself, call TAG_NAMES with the /STRUCTURE_NAME keyword.

Example

Using tag indices and the above-mentioned functions, we specify a procedure that reads into a structure from the keyboard. The procedure prompts the user with the type, structure, and tag name of each field within the structure.

;A procedure to read into a structure, S, from the keyboard with  
;prompts. 
PRO READ_STRUCTURE, S 
 
;Get the names of the tags. 
NAMES = TAG_NAMES(S) 
;Loop for each field. 
FOR I = 0, N_TAGS(S) - 1 DO BEGIN 
   ;Define variable A of same type and structure as the i-th field. 
   A = S.(I) 
 
   ;Use HELP to print the attributes of the field. Prompt user with  
   ;tag name of this field, and then read into variable A. S.(I) =  
   ;A. Store back into structure from A.  
   HELP, S.(I) 
 
   READ, 'Enter Value For Field ', NAMES[I], ': ', A 
   S.(I) = A 
ENDFOR 
END 

Note
In the above procedure, the READ procedure reads into the variable A rather than S.(I) because S.(I) is an expression, not a simple variable reference. Expressions are passed by value; variables are passed by reference. The READ procedure prompts the user with parameters passed by value and reads into parameters passed by reference.