Type as Function Parameter

BlitzMax Forums/BlitzMax Programming/Type as Function Parameter

Hezkore(Posted 2011) [#1]
Is it possible to have a Type as a Function parameter?
What I want to do is something like this:
Type MyType
   Method Start()
      Print("Hello")
   EndMethod
EndType

Function RunType(SomeType:Type)
   Local nType:SomeType=New SomeType
   nType.Start()
EndFunction

RunType(MyType)
A shiny gold doubloon for anyone that solves this!

UPDATE: After some reading about "reflection" I have solved it.
I guess that gold doubloon will be mine forever! :3

Last edited 2011


JazzieB(Posted 2011) [#2]
Yes, and you don't need to use reflection...

SuperStrict

Type alien
	Field name:String
	
	Function Create:alien()
		Local a:alien=New alien
		a.name="Bob"
		Return a
	EndFunction
EndType

Function ShowName(a:alien)
	Print "This alien's name is "+a.name
EndFunction

Local bob:alien=alien.Create()

ShowName(bob)



Brucey(Posted 2011) [#3]
Except Jazzie, that doesn't solve his problem.
He is trying to pass a "type" into a function, rather than an instance of a type. In BlitzMax, this requires use of reflection to accomplish it.


jsp(Posted 2011) [#4]
Sometimes you have already one instance of a type and now you need another one.
In that case you don't need reflection.

Example:
Type MyType
   Method Start()
      Print("Hello")
   EndMethod
EndType

Type YourType
   Method Start()
      Print("Blub")
   EndMethod
EndType


Function RunType:Object(SomeType:Object)
   Local nType:Object = New SomeType
   If MyType(nType) Then MyType(nType).Start()
   If YourType(nType) Then YourType(nType).Start()
	Return nType
EndFunction

First:MyType = New MyType
Second:YourType = New YourType

AnotherFirst:Object = RunType(First)
AnotherSecond:Object = RunType(Second)



Brucey(Posted 2011) [#5]
But there you have a lot of assumptions about the specific types you are handling in the function...

And if you have 10 different types? A nice long list of If statements...


jsp(Posted 2011) [#6]
And if you have 10 different types? A nice long list of If statements...


It all depends what you want of course. This is just an example!
If you add your type to a TList and later EachIn through that list for a certain type, it's absolute OK.
No extra overhead is needed.


TomToad(Posted 2011) [#7]
You can use Abstract.
SuperStrict

Type OurType Abstract
	Method Start() Abstract
End Type

Type MyType Extends OurType
	Method Start()
		Print "I'm in MyType"
	End Method
End Type

Type YourType Extends ourType
	Method Start()
		Print "I'm in YourType"
	End Method
End Type

Local Mine:MyType = New MyType
Local Yours:YourType = New YourType

PrintType(Mine)
PrintType(Yours)

Function PrintType(Ours:OurType)
	Ours.Start()
End Function


Edit: Just checked the OP, I guess this wasn't exactly what he wanted.

Last edited 2011