New() method

BlitzMax Forums/BlitzMax Beginners Area/New() method

GfK(Posted 2008) [#1]
I'm probably having a major brainfart here, hence, Beginner's Area.

Suppose I have code like:
myVar:myType = New myType

...how do I pass parameters to the New() method? I know I can easily call another method manually after I create the object but surely there's a way you can do this by simply using New()? Don't want to use two lines of code if I can do the same job with one.


Htbaa(Posted 2008) [#2]
You can't, not in BlitzMax.

Add a Create function to your Type. e.h.

Type TSomething
     Field x:Int
     Field y:Int

     Function Create:TSomething(x:Int,y:Int)
         Local obj:TSomething = New TSomething
         obj.x = x
         obj.y = y
         Return obj
     EndFunction
EndType

Local myVar:TSomething = TSomething.Create(100,100)



GfK(Posted 2008) [#3]
Oh good, I'm not going insane then. :)

Thx!


Htbaa(Posted 2008) [#4]
Hehehe :-). Well, it sorta is kind of weird that you can't give the constructor any parameters.


Otus(Posted 2008) [#5]
But if you could, BlitzMax had to support overloading.


Htbaa(Posted 2008) [#6]
Which would be even nicer.


GfK(Posted 2008) [#7]
Maybe worth mentioning, I found a 'solution' from Dreamora here.

Trouble is, it doesn't actually work. Did it ever?

It'd be nice if incorrect or blatantly wrong information could be removed to prevent the place getting cluttered up with useless info. It only serves to cause confusion.

BTW: I'm using Htbaa's solution and all is well. :)


Koriolis(Posted 2008) [#8]
Using an init method certainly DOES work, the only thing is that in the example given by Dreamora he forgot to give the return type. Simply add ":test" after "init".


GfK(Posted 2008) [#9]
That's exactly my point. The code is wrong. Nobody pulled him up on the fact that it didn't work - someone even thanked him for it.

(He also didn't include any Field definitions for X and Y, but I spotted that)

I think if you're going to post a solution to a problem, then you should either:

A) Make it clear that the code is for guidance and is untested, or
B) Test it and make sure it works.

By not doing either, you can cause more confusion than you solve.


Koriolis(Posted 2008) [#10]
OK. I hadn't the impression that it was actually your point, given how you asked if it ever worked. Obviously it nerver worked as is.


Sledge(Posted 2008) [#11]
BTW: I'm using Htbaa's solution and all is well. :)
As 'Create' is already a keyword I tend to use 'Make' -- probably just paranoia but hey ho. :)


CS_TBL(Posted 2008) [#12]
.init
.setup
.make


Perturbatio(Posted 2008) [#13]
As 'Create' is already a keyword I tend to use 'Make' -- probably just paranoia but hey ho. :)


Create is only highlighted because some of the BRL types make use of the same concept. It's not a reserved keyword.