Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare 2D arrays in Haxe?

Tags:

haxe

In other programming languages, I can use int array[23][23] to declare a 2D array with 23 elements in each dimension. How do I achieve the same thing in Haxe?

Currently I need to do this:

var arr:Array<Array<Int>> = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];

But when the array grows to a larger size, it becomes infeasible for me to declare it like that anymore.

like image 973
sub_o Avatar asked May 01 '13 11:05

sub_o


People also ask

How do you declare a 2D array?

To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.


1 Answers

The best way to do this is to take advantage of array comprehensions, provided in Haxe 3:

var bigArray:Array<Array<Int>> = [for (x in 0...10) [for (y in 0...10) 0]];

Array comprehensions are a really nice and condensed syntax for making arrays. The above code would make a 10x10 array, filled with 0s. You can read more about them here.

If you're running Haxe 2 for some reason, the best way to do it would be to fill them out with for loops, as suggested previously.

like image 71
thedayturns Avatar answered Sep 24 '22 13:09

thedayturns