Creating new arrays

Community Forums/Monkey2 Talk/Creating new arrays

Leo Santos(Posted 2016) [#1]
(Posted in Monkey2's forums, posting here as well)

Ok, really basic. How do you create a new array and add all values at once (without iterating)?

In Monkey1 it used to be:

Local frames := [0,1,2,3,4]


In Monkey2 that doesn’t work. I also tried this:
Local frames := New Int[5]
frames = [0,1,2,3,4]


Doesn’t work either.
Help!


therevills(Posted 2016) [#2]
Try:
Local frames := New Int[]( 0, 1, 2, 3, 4 )


Check out this page:
http://monkey2.monkey-x.com/2015/09/09/monkey1-to-monkey2/


Leo Santos(Posted 2016) [#3]
That works, thanks!!! That page is quite well hidden... :-)
It's the kind of material that needs to be in the language guide.

Cheers!


Nobuyuki(Posted 2016) [#4]
would be nice to see the old initializer syntax return, if only for arguments which take an array, seeing as how that looked a bit nicer to my eyes and was definitely less to type... But then, I guess that goes against my personal principle of "verbosity in the right places", since this syntax does seem a bit more obvious as to what's going on.


marksibly(Posted 2016) [#5]
The problem with the old syntax was all elements had to be of *exactly* the same type or it wouldn't be able to work out the array type.

So you ended up having to 'upcast' stuff a lot, eg (mx1):

Local bases:=[ Base( derived1 ),Base( derived2 ),Base( derived3 ) ]

...or....

Local floats:=[ 1.0,1.0,0.0,1.0 ] 'why can't I use ints here?!?

The new syntax fixes that, eg:

Local bases:=New Base[]( derived1,derived2,derived3 )
Local floats:=New Float[]( 1,1,0,1 )

IMO a big imrpovement, and sometimes less typing.

I guess the old syntax could be added too, but nah...


Leo Santos(Posted 2016) [#6]
I agree with Nobuyuki, the only time I miss the old syntax is when I'm passing arrays as arguments to functions or fields, so:

sprite.AddAnimationClip( index, [0,1,2,3,4,4,4,3,4,3,4,3,2,1,0] )

sprite.collisionLayers = [ layer1, layer2, layer3 ]


Becomes:

sprite.AddAnimationClip( index, New Int[]( [0,1,2,3,4,4,4,3,4,3,4,3,2,1,0] ) )

sprite.collisionLayers = New Layer[]( layer1, layer2, layer3 )


Which is harder to read, specially if it's in the middle of a lot of others arguments.
Would be nice if the old way was supported, even if with limitations.

Thanks!
Leo.