How to determine if TList item is a string?

BlitzMax Forums/BlitzMax Programming/How to determine if TList item is a string?

Russell(Posted 2007) [#1]
I like the idea that objects of various types can be added to the same TList, but what is the best way to then determine what is what in an EachIn loop? What am I doing wrong here?
Type TType
	Field blah
End Type

Type TType2
	Field blah2:Float
End Type

t:TType = New TType
s:TType2 = New TType2

Local list:TList=New TList
list.AddLast t
list.AddLast s

For Local b:TList=EachIn list
	If TType(b)
		Print b.blah
	Else
		Print b.blah2
	EndIf
Next

I thought that 'TType()' would return a true or false depending on whether the object in the parentheses was that type. Perhaps I do not understand it completely? What I want to do is be able to add several different types of objects, including strings, to a list and then do different things with each object depending on what type it is.

Any suggestions?

Russell


SSS(Posted 2007) [#2]
What you're doing wrong is declaring b as a TList type. If you want to get all the objects in the list you have to do,
For Local b:Object=EachIn list
	If TType(b)
		Print b.blah
	Else
		Print b.blah2
	EndIf
Next



Russell(Posted 2007) [#3]
If I make the change you suggest, I get "Identifier 'blah' not found".

Any ideas?

Russell


SebHoll(Posted 2007) [#4]
You would need to cast the variable, by wrapping TType() around the b. Or if you just wanted to loop through objects of a specific type simply declare the loop variable as the item you want (in this case, all strings in the list will be returned):

For Local b:String=EachIn list
	Print b
Next
The same for looping through TType:

For Local b:TType=EachIn list
	Print b.blah
Next



Azathoth(Posted 2007) [#5]
TType() will return an instance if it is a type of TType or null if its not.

b is also one of the elements of the TList, not a TList itself.

Edit: You could also just convert it once and store the instance/null in a variable

Type TType
	Field blah
End Type

Type TType2
	Field blah2:Float
End Type

Local t:TType = New TType
Local s:TType2 = New TType2

Local list:TList=New TList
list.AddLast t
list.AddLast s

For Local b:Object=EachIn list
	If TType(b)
		Print TType(b).blah
	ElseIf TType2(b)
		Print TType2(b).blah2
	EndIf
Next



Russell(Posted 2007) [#6]
Thanks Azathoth (Azathoth?), that's just what I needed! Works great!

Russell


Grey Alien(Posted 2007) [#7]
Yeah that typecasting to find out the type is a neat trick.