4

In a previous function, I create and return a hash. Upon doing this, it returns the hash as a structure, and I use this as an input to this following function.

myStruct's tags are each a structure, each with a name and dataType tag.

I'm trying to iterate through each tag to find at which 'name' a certain dataType occurs.

pro plotter, myStruct

    numtags = n_tags(myStruct) 
    names = tag_names(myStruct)
    for varID = 0, numtags do begin
       if ( strcmp( myStruct.(names[varID]).datatype, 'Temperature, Head 1')) then print, varID

    endfor

 end

I get the following error after trying to run this: "Type conversion error: Unable to convert given STRING to Long."

What is causing this error? Can I access the tag using a variable name?

Tim
  • 1,659
  • 1
  • 21
  • 33
Lauren R.
  • 41
  • 2

2 Answers2

5

You can do this, but not quite how you are. I think this is the problem:

myStruct.(names[varID])

since names[varID] is a string.

I'm assuming myStruct looks something like this:

myStruct = { tag1: {data:0L, datatype:'Some type'}, tag2: {data:1L, datatype:'Temperature, Head 1'}}

In general, you can access structures via the tag name or the index. So,

myStruct.(0)
myStruct.tag1

will both give you the first value in the first tag of the structure (and you can increment the index as needed for other tags). In this case, these will yield the structure "stored" in tag1.

If so, then this should work:

pro plotter, myStruct

numtags = n_tags(myStruct) 
names = tag_names(myStruct)
for varID = 0, numtags-1 do begin
   if ( strcmp( myStruct.(names[varID]).datatype, 'Temperature, Head 1')) then print, names[varID]
endfor

end
2

You should index your structure with the variable varID not names[varID], thus your code should look like:

pro plotter, myStruct

numtags = n_tags(myStruct) 
names   = tag_names(myStruct)
for varID=0L, numtags - 1L do begin
   if (strcmp( myStruct.(varID).datatype, 'Temperature, Head 1')) then print, names[varID]
endfor

end

Note that you also need to change the max index to which the FOR loop can cycle to prevent an indexing error crash. This is because IDL starts indexing from zero, not one.

honeste_vivere
  • 308
  • 5
  • 11