New() method
BlitzMax Forums/BlitzMax Beginners Area/New() method
| ||
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. |
| ||
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) |
| ||
Oh good, I'm not going insane then. :) Thx! |
| ||
Hehehe :-). Well, it sorta is kind of weird that you can't give the constructor any parameters. |
| ||
But if you could, BlitzMax had to support overloading. |
| ||
Which would be even nicer. |
| ||
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. :) |
| ||
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". |
| ||
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. |
| ||
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. |
| ||
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. :) |
| ||
.init .setup .make |
| ||
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. |