Page 1 of 1

Dynamic variable name.. possible?

Posted: 21 Feb 2012, 04:07
by thequickbfox
Hi,
I'm used to Flash Actionscript2 where you can dynamically refer to a variable.
eg. setting a value in an array.

c1 = new Array(0,0,0,0,0);
x = 1;
eval("c"+x)[2] = 5;

Is anything like this possible in NXC.?

Context: I've written a "Connect 4" game playing robot. The gameboard has 7columns and 6rows. Too many for NXC support for multidimensional arrays (4 max?). So I just created 7 column arrays (c1 - c7) and now I'm running out of memory because I've used so many switch cases to deal with each of these columns, and I haven't even got the robot playing with any smarts yet (It just randomly picks a column for its turn). If I could do something like the above, I could vastly reduce the number of lines of code.

Re: Dynamic variable name.. possible?

Posted: 21 Feb 2012, 04:13
by afanofosc
A connect for board is simply a 2d array.

Code: Select all

byte c4board[7][7];
That's only 49 bytes. You can set the value to 0, 1, or 2 depending on whether the cell is empty, or filled by player 1 or player 2.

John Hansen

Re: Dynamic variable name.. possible?

Posted: 21 Feb 2012, 04:35
by thequickbfox
Thanks for that.

So do I have to upgrade to the enhanced firmware to get multidimensional array support?

Re: Dynamic variable name.. possible?

Posted: 21 Feb 2012, 07:56
by HaWe
it's always better to use the efw when using NXC ;)

another way for handling the 7x6 board is like I'm doing for my 8x8 chess board:
Just use a 1-dim array[42]!

Re: Dynamic variable name.. possible?

Posted: 21 Feb 2012, 15:37
by afanofosc
Doc's suggestion is a great one - even if you are using the enhanced firmware. You can just calculate the index into the 1-d array as a simple function of R and C (i.e., row and column). The enhanced firmware is required if you want to use 2-d arrays, sadly, due to the REPLACE opcode bug that has never been fixed in spite of my efforts to convince LEGO and NI to fix it. 2d array support is not considered to be a requirement for NXT-G users so the standard firmware does not need to support that highly advanced and little used technique.

John Hansen