question about custom typed array and assigning elements

Previous topic - Next topic

BdR

Hi all :good: I have a question about array of types, and assignment of these array elements.

If you have an array of a custom type, you can assign the values of an element with a variable, if the variable is of the same type. See code example below, it works fine and as expected.

Code (glbasic) Select

TYPE TLevel
  Tiles[5][5]
  Difficulty
  Description$
ENDTYPE

GLOBAL LevelSet[] AS TLevel

DIM LevelSet[3]

LOCAL i, x, y
LOCAL tmpLevel AS TLevel

// initialise dummie test levels
FOR i = 0 TO 2
  LevelSet[i].Description$ = "Level "+i
  FOR y = 0 TO 4
    FOR x = 0 TO 4
      LevelSet[i].Tiles[x][y] = i
    NEXT //y
  NEXT //x
NEXT //i

// now move the items array around
tmpLevel = LevelSet[0]
LevelSet[0] = LevelSet[1]
LevelSet[1] = LevelSet[2]
LevelSet[2] = tmpLevel

// draw dummie levels
FOR i = 0 TO 2
  PRINT LevelSet[i].Description$, (i*80), 0
  FOR y = 0 TO 4
    FOR x = 0 TO 4
      PRINT LevelSet[i].Tiles[x][y], (i*80) + x*8, 32+y*8
    NEXT //y
  NEXT //x
NEXT //i

// display the results
SHOWSCREEN
KEYWAIT

My question is, does it actually do the assignment of all array elements (each integer in Tiles[][] etc.) or are the pointers switched around? Or are there are any other potential pitfalls I need to be aware of, when assigning typed-array elements this way?

I'd like to know, before I use this "trick" extensivly in my game code.

FutureCow

Gernot would be able to give you a definitive answer. However, I've flexed my extremely rusty C++ skills and assuming I'm reading the code correctly, it looks like it does the assignment of all array elements.

From the compilation of your code :-

Code (glbasic) Select

class TLevel
{
public:
DGIntArray Tiles;
DGInt Difficulty;
DGStr Description_Str;
TLevel()
{
DIM (Tiles,5 ,5);
Difficulty = 0;
}
TLevel(const TLevel& _in_)
{*this = _in_;}

TLevel& operator=(const TLevel& _in_)
{
this->Tiles = _in_.Tiles;
this->Difficulty = _in_.Difficulty;
this->Description_Str = _in_.Description_Str;
return *this;
}

Kitty Hello

Code (glbasic) Select

TYPE TT
a;b;c[]
ENDTYPE

LOCAL t1 AS TT, t2 AS TT

Init(t2) // Directly access the members as a reference
t2 = t1 // copies all variables from t2 to t1, does DIM for arrays and foreach for the values. (sort of)


FUNCTION Init: tp AS TT // init by a reference
tp.a = 15
ENDFUNCTION


I hope that makes it clear. I do what you do a lot, too (especially for UNDO data). It's fine.