6

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.

cHao
  • 84,970
  • 20
  • 145
  • 172
Carthage
  • 77
  • 1
  • 6
  • 1
    Nice to see another IDL programmer on SO! Maybe someday we can reclaim 'our' tag from the likes of those CORBA programmers.... – Jim Lewis May 10 '10 at 22:16

1 Answers1

8

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.

Jim Lewis
  • 43,505
  • 7
  • 82
  • 96