Dynamic variable name.. possible?

Discussion specific to NXT-G, NXC, NBC, RobotC, Lejos, and more.
Post Reply
thequickbfox
Posts: 5
Joined: 01 Feb 2012, 00:56

Dynamic variable name.. possible?

Post 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.
afanofosc
Site Admin
Posts: 1256
Joined: 26 Sep 2010, 19:36
Location: Nashville, TN
Contact:

Re: Dynamic variable name.. possible?

Post 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
Multi-platform LEGO MINDSTORMS programming
http://bricxcc.sourceforge.net/
thequickbfox
Posts: 5
Joined: 01 Feb 2012, 00:56

Re: Dynamic variable name.. possible?

Post by thequickbfox »

Thanks for that.

So do I have to upgrade to the enhanced firmware to get multidimensional array support?
HaWe
Posts: 2500
Joined: 04 Nov 2014, 19:00

Re: Dynamic variable name.. possible?

Post 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]!
afanofosc
Site Admin
Posts: 1256
Joined: 26 Sep 2010, 19:36
Location: Nashville, TN
Contact:

Re: Dynamic variable name.. possible?

Post 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
Multi-platform LEGO MINDSTORMS programming
http://bricxcc.sourceforge.net/
Post Reply

Who is online

Users browsing this forum: No registered users and 4 guests