# Creating 2d array in gamemaker from code

According to GameMaker2 arrays documentation, GML has 2d arrays. At the same time I could not find any references how can I create 2d array from code. I tried doing

board = array_create(global.MAX_HEIGHT);
for(var i = 0; i < global.MAX_HEIGHT; i++){
board[i] = array_create(global.MAX_WIDTH);
}


but that seems to have created a 1d array of 1d arrays, meaning I cannot access them using board[x, y] (if I try it doesn't assign values properly) , or even board[x][y] (compilation error). Is there a way to dynamically create 2d array? Or to access this array more elegantly, instead of having to use

inside_array = board[i];
inside_array[j] = value;


The answer is- don't initialize the array, just access it. It will dynamically create 2d array. So to initialize 2d array to 0s, do

for(var i = 0; i < global.MAX_HEIGHT; i++){
for(var j = 0; j < global.MAX_WIDTH; j ++){
board[i, j] = 0;
}
}

• If this resolved your issue, consider accepting as an answer to your question. Oct 17, 2019 at 23:33

The documentation says you "access multi-dimension arrays with extra sets of brackets". If you got a compiler error, you must have done something else wrong.

2d arrays are documented to be accessed like so:

array2d[i][j]=1;

• IIRC, Gamemaker Studio 2 has changed their multidimensional arrays, so now you can have multiple 1D arrays, and put these in an array to create 2D arrays that way. Aug 23, 2021 at 8:35
• When writing "The documentation says" in a post, it's always a good idea to add a link to said documentation, it helps the other visitors understand potential solutions better. Aug 31, 2021 at 13:57

I prefer to use repeat instead of for, but you can enjoy the logic.

Basically you will use one loop inside another.

Code:

repeat(global.MAX_HEIGHT){
i+=1;
repeat(global.MAX_WIDTH){
j+=1;
board[i,j]=0;
}
j=0;
}

i=0;
j=0;


Then remember to reset the value of i and j.

• Ew!? Why emulate a for-loop using repeat when you could just use for in the first place? This is what for is made for (no pun intended). Jul 15, 2020 at 9:41
• @Charanor Another user responded using "for". The questioner did not accept the answer for some reason, even though the answer was apparently right. It is not because you don't like it that nobody else will like it. I find it easier to read/understand code with "repeat" than with "for". As a programmer you should know that there are several solutions to a single problem. Jul 15, 2020 at 22:40