Multi dimensionnal Array in OpenFl

Hello,

how to create multi dimensionnal Array in openfl

var array:Array = new Array();  
array.push( [2, 4] );
array.push( [5, 9] );
trace( array[1][1] );

Thanks

These should work:

var array = [ [ 2, 4 ], [ 5, 9 ] ];
var array:Array<Array<Int>> = [ [ 2, 4 ], [ 5, 9 ] ];

or

var array = [];
array.push ([ 2, 4 ]);
array.push ([ 5, 9 ]);

var array:Array<Array<Int>> = new Array<Array<Int>> ();
array.push ([ 2, 4 ]);
array.push ([ 5, 9 ]);

I prefer to rely on type inference, because I think it makes code look cleaner :grinning:

with Array dynamic it’s possible ?

var array:Array<Dynamic> = new Array<Dynamic> (); ???

Yes, but don’t do that if you can avoid it.

//Do this:
var array = [ [ 2, 4 ], [ 5, 9 ] ];

//Or do this:
var array:Array<Array<Int>> = [];
array.push ([ 2, 4 ]);
array.push ([ 5, 9 ]);

//But don't do this:
var array = [];
array.push ([ 2, 4 ]);
array.push ([ 5, 9 ]);

//And don't do this:
var array:Array<Dynamic> = [];

Downside is that they are a bit slower?!

That sounds quite absolute, and thinking about my code i get a bit nervous ^^
Some details would help :slight_smile:

Sorry for the confusion. I was trying to correct in4core, but it isn’t really an absolute rule. That’s why I said “if you can avoid it.”

If you need multiple different types in the same array, then you can’t avoid it, and you should go ahead. But if you’re only using one type, and you know that type at compile time, then don’t use Dynamic. It hurts performance and may prevent the compiler from noticing errors.

1 Like

Heres how I initialize an array when doing map tiles:

mapArray = [for (x in 0…mapWidth) [for (y in 0…mapHeight) -1]];

what is the difference between “Array<Int>” and “openfl.Vector<Int>” ?

On the Flash target, Array<Int> is a sparse array, meaning you can skip indices. This makes it somewhat less efficient.

We also support vector.length = 0 (without allocating a new underlying array) which is not available in Haxe arrays