Tlists containing different types

BlitzMax Forums/BlitzMax Programming/Tlists containing different types

necky(Posted 2008) [#1]
Is it possible for Tlists to containing different types?
The below code goes someway to hinting this is possible as I can add the 'tTestA' and 'tTestB' types to my single 'test' TList but I don't know how to go about running through this list using a 'for' loop.
I`m pretty new on this level of type-based coding so all help is much welcomed.




Grey Alien(Posted 2008) [#2]
You need to "typecast" the plain Object into the actual object type that it is so that the name will be recognised. E.g.

For Local loop:Object=EachIn Test
	If ttesta(loop) Then Print ttesta(loop).name
	If ttestb(loop) Then Print "B"
Next


Maybe a better method would be to define a base class with an ObjectType field that you can set to a value. Then extended the base class for all your other classes. Then inside the For loop you can simple typecast the loop object as your base class type and then check the ObjectType field before calling specific actions. However, it would be best for something like Draw() of the bass class had a Draw() method that you override in the extended classes, so whenever you call the Draw() it calls the correct one. This is called Polymorphism and I probably have not explained it very well if you don't already know about it...


necky(Posted 2008) [#3]
Exactly what I was after.
Thanks:)


Kurator(Posted 2008) [#4]
The Ohter way is to use Polymorphism:
Type tTestBase
	Field Name:String
EndType

Type tTestA Extends tTestBase
	Method New()
		name = "TESTA"
	EndMethod
End Type

Type tTestB Extends tTestBase
	Method New()
		name = "TESTB"
	EndMethod
End Type


Global Test:TList=New TList

Test.addlast (New tTestA)
Test.addlast (New tTestB)
Test.addlast (New tTestB)
Test.addlast (New tTestA)
Test.addlast (New tTestB)


For Local loop:tTestBase = EachIn Test			   
	Print loop.name							'common field for both types
Next



Grey Alien(Posted 2008) [#5]
That's what I said dude ;-) but good example.


Kurator(Posted 2008) [#6]
oh, indeed - I should not stop to tread after posted code examples :)