Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDL: Accessing struct fields using field names stored in variables?

If I have a struct with a fieldname 'fieldname', is it possible to access the data in that field using only the variable?

ie.

x = 'fieldname'

is it possible to do

data = struct.(x) in some way? I want to use the string in x as the field name.

like image 225
Carthage Avatar asked May 10 '10 20:05

Carthage


1 Answers

Yes, this is possible using the TAG_NAMES function:

tnames=TAG_NAMES(struct)
tindex=WHERE(STRCMP(tnames,'fieldname') EQ 1)
data=struct.(tindex)

The call to TAG_NAMES returns an array of strings representing the tags defined in struct. The WHERE statement returns the index in tnames of a string matching 'fieldname'. Finally, the index is passed to the struct.(tindex) operation, which extracts a field by its numeric tag index.

Of course, in a real application you'd want to check whether tindex was successfully matched to something, otherwise IDL will choke on the structure lookup with an index of -1.

like image 54
Jim Lewis Avatar answered Nov 17 '22 19:11

Jim Lewis