Page 1 of 1

Are 2D arrays Global?

PostPosted: Tue Aug 05, 2008 6:19 pm
by akhad
Ok, my grappling match with arrays goes on and I've started using a 2d array. As these have to be manually set from an actor script, I can't seem to reference them from outside of the actor that defines it. My array is such:

int Grid [3][5] = {
{ 2,1,3,4,3}, // 5 numbers across....
{ 2,4,3,1,2},
{ 1,3,2,4,1}, } // and 3 rows down *(just typed this in from memory, ignore typo's etc)*

How do I now access i.e the value of Grid [3] [3] from elsewhere in the program?

Re: Are 2D arrays Global?

PostPosted: Tue Aug 05, 2008 11:47 pm
by feral
arrays are only global if you set them in a global script ( or as a global variable using the variables button)

simply create your array in any "global script" and it will be accessible from all actors.

any array's, variables, etc created in an actor script are "local" ... meaning they are only accessible in that particular script .

Re: Are 2D arrays Global?

PostPosted: Wed Aug 06, 2008 2:42 am
by Fuzzy
You'll need two reference variables as well.
Code: Select all
i = 3; // max 5
j = 2; // never more than 3
Grid[i][j] = 345;


The problem with this approach, especially with a screen sized array is that you have to make sure you dont/cant address cells outside the array, or you get a nasty error. You end up with a whole bunch of if statements, which is the original reason I put that quote in my sig.

So a more clever way to approach that is to use a 1D array and calculate your 2D location when you access it.

to get a 2D location in a 1D array, consider that you'll need to keep a record(variable) of how big the x size really is. In our case, i can be no greater than 5, right? So MaxGridX = 5.

Now we just have to multiply MaxGridX by current j to get our location vertically. then we add our offset, which is variable i in this case. I'll code it up..

Code: Select all
int Grid[5*3]; // yeah you can do this to remind yourself, otherwise use 15
int MaxGridX = 5;
int i = 3;
int j = 2;

Grid[i+MaxGridX*j] = 345;


Thats how that works. Now we only have to have if statements to make sure that we dont fall out of the top and bottom of the array. The sides are protected. You only have to use

Code: Select all
if((i+MaxGridX*j) < 0)
    { // problem solving code here} // our number is too small
if((i+MaxGridX*j) > (sizeof(Grid)))
    { // problem solving code here} // our number is too big


Which is much shorter.

But I will give you a tip. There is a way to eliminate and shorten those as well. Can you figure it out?