Create function to create object with parameters

Monkey Forums/Monkey Programming/Create function to create object with parameters

GfK(Posted 2011) [#1]
This is converted from some Blitzmax code - it looks right, but it isn't because I get a Null Object Access error - what's wrong?:
Strict

Import mojo

Function Main:Int()
	New myGame
End Function

Class myGame Extends App
	Field test:myClass
	
	Method OnCreate:Int()
		Self.test = myClass.Create(100,100)
	End Method
End Class

Class myClass
	Field x:Int
	Field y:Int
	
	Function Create:myClass(x:Int,y:Int)
		Local t:myClass
		t.x = x
		t.y = y
		Return t
	End Function
End Class



Volker(Posted 2011) [#2]
You are defining t as myClass, but do not create a new object
Local t:myClass=new myClass 

does it.


GfK(Posted 2011) [#3]
Oh Christ I'm such a spaz! I think I'm looking so hard for the stuff that's changed, I'm starting to miss the obvious stuff.

Thanks!


DruggedBunny(Posted 2011) [#4]
Just to demonstrate an alternative, you can simplify this by using the New method in place of a Create function now:

Strict

Import mojo

Function Main:Int()
	New myGame
End Function

Class myGame Extends App
	Field test:myClass
	
	Method OnCreate:Int()
		Self.test = New myClass(100,100)
		Print test.x
		Print test.y
	End Method
End Class

Class myClass
	Field x:Int
	Field y:Int
	
	Method New (xx:Int,yy:Int)
		x = xx
		y = yy
	End Method
End Class



GfK(Posted 2011) [#5]
Oh, that's a bit neater! Ironically, that's how I always wanted to do it in Blitzmax.


dmaz(Posted 2011) [#6]
don't completely discount "Create" methods and it's a great place for any pooling infrastructure.


DruggedBunny(Posted 2011) [#7]
Actually, for what it's worth, I just realised that the Self is redundant here:

' Self.test = New myClass(100,100)
test = New myClass(100,100)


... but what dmaz says is true, too.