Type Comparison Through Functions Possible?

BlitzMax Forums/BlitzMax Programming/Type Comparison Through Functions Possible?

HrdNutz(Posted 2008) [#1]
Hi,

I hope to maybe get some help with comparing polymorphed object types through a function call.

Please consider this pseudo code. 3 objects of derived types are created and stored in Base type pointer, then added to a list.
Type TBase
Type TA extends TBase
Type TB extends TBase
Type TC extends TBase

a:TBase = new TA
b:TBase = new TB
c:TBase = new TC

list.add(a)
list.add(b)
list.add(c)



So the list is populated with 3 differend sub types all hiding under base type. What i really need is to implement some sort of method that will accept one of the derived types as argument, loop through the list, and return the same type object if found.

I can do this:
' i want to check if a type exists in the list
for o = eachin List
if TA(o) ' object is of type TA
if TB(o) ' object is of type TB
if TC(o) ' object is of type TC
next


' but I need to encapsulate that loop into a method, and somehow return proper type, so I want to do this:
o:TA = GetType(of type TA somehow)

Method GetType:TBase( some type)
 for o = eachin List
  ' any way to pass a type and do a cast like this????
  if some type(o) return o
 next
End method


Any way of doing this? I am trying to implement a component based entity approach, and need method that will Return a component of an entity if it exists in the list.

TIA, and i hope this makes sense.


Rone(Posted 2008) [#2]
Maybe so:


Type TMyType
	Field bla$
End Type

type TMyTypeA extends TMyType
endtype 

type TMyTypeB extends TMyType
endtype 

function GetType:object(obj:object, list:tList)
	Local id:TTypeId=TTypeId.ForObject( obj )
	for local o:object = eachin list
		local id2:TTypeId=TTypeId.ForObject( o )
		if id.Name() = id2.Name() then 
			return o
		endif 
	next
end function

'###################################################
' Test

Local obj1:TMyType =New TMyType
obj1.bla = "1"

Local obj2:TMyTypeA =New TMyTypeA 
obj2.bla = "2"

Local obj3:TMyTypeB =New TMyTypeB 
obj3.bla = "3"

local list:Tlist = new TList
list.AddLast(obj1)
list.AddLast(obj2)
list.AddLast(obj3)


local result:TMyType = TMyType( GetType( new TMytype, list ) )
print result.bla



HrdNutz(Posted 2008) [#3]
That was really helpful, thanks a bunch!!!
I didn't know I could do reflections with bmax, awesome. heres my simple functoin now :D

Method GetType:object(typeName:String)
  Local tid:TTypeId = TTypeId.ForName(typeName)
  Local oid:TTypeId 
  For local o:object = eachin List
    oid = TTypeId.ForObject(o)
    if oid = tid return o
  Next
End Method


Thanks again!


plash(Posted 2008) [#4]
You could also use metadata, but I suppose that is just as good.