2D Array

How do I simulate an 2D array?

You need to create an array, then populate each element in the array with another array. This should work:

`//3x3 array
const ARRAY_X = 3
const ARRAY_Y = 3

ticTacToe <- array(ARRAY_Y);
foreach(y in ticTacToe) {
y = array(ARRAY_X);
}

function setPiece(x,y, token) {
ticTacToe[x][y] = token;
}`

thanks @beardedinventor,

I couldn’t find anything anywhere on this.
you made me very happy

We should probably have something in the dev center about this - I’ll add a task to make sure it gets looked at :slight_smile:

`const ARRAY_X = 3
const ARRAY_Y = 3

ticTacToe <- array(ARRAY_Y);
foreach(y in ticTacToe) {
y = array(ARRAY_X);
}

function setPiece(x,y, token) {
ticTacToe[y][x] = token;
}

setPiece(1,1, 1);`

trying this code I get this:

2014-08-06 02:06:52 UTC+2 [Device] ERROR: trying to set 'null' 2014-08-06 02:06:52 UTC+2 [Device] ERROR: at setPiece:11 2014-08-06 02:06:52 UTC+2 [Device] ERROR: from main:14

Whoops - I guess you can’t use a foreach loop - that’s what I get for posting untested code in the forums :frowning:

This works:
`const ARRAY_X = 3
const ARRAY_Y = 3

ticTacToe <- array(ARRAY_Y);
for(local i = 0; i < ARRAY_Y; i++) {
ticTacToe[i] = array(ARRAY_X);
}

function setPiece(x,y, token) {
ticTacToe[y][x] = token;
}

setPiece(1,1,1);
server.log(http.jsonencode(ticTacToe));`

Now it works, thanks.
For the record: why no foreach loop?

Because in “foreach (y in ticTacToe)”, the variable y is a new local which is initialised from the actual array member. It isn’t a reference back to the array member. So when beardedinventor’s original code assigned to y, that didn’t change the array ticTacToe as he’d hoped.

You could do
foreach (i,v in ticTacToe) { ticTacToe[i] = array(ARRAY_X); }
or even
ticTacToe.apply(@(y) array(ARRAY_X));
but they’re no clearer than the for-loop version really.

Peter

thank you Peter,

I could have known that I shouldn’t have asked. Way over my head.
But I like your examples. Maybe some day I’ll understand…