# 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. – Boneco Sinforoso Oct 17 '19 at 23:33

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). – Charanor Jul 15 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. – Boneco Sinforoso Jul 15 at 22:40