Arrays in Types?

Previous topic - Next topic

matty47

Are they allowed.
For instance I want to do something like this
Code (glbasic) Select

CONSTANT MaxDims=3

TYPE Point
     Loc[MaxDims]
ENDTYPE

.....................................
//then later do

LOCAL P1 AS POINT
.......................................
FOR i = 0 to MaxDims
      IF P1.Loc[i] ................

Now I know this code won't work but the compiler issues an error for the Loc[MaxDims] line
Any answers greatly appreciated
Thanks
Matthew

Qedo

Try:

CONSTANT MaxDims=3
TYPE Point
     Loc[]
ENDTYPE
LOCAL P1 AS Point
REDIM P1.Loc[MaxDims]
FOR i = 0 TO MaxDims-1
      IF P1.Loc=0 THEN P1.Loc=10
NEXT

Ciao

matty47

Tried that - didn't seem to work.
I tried changing my attack and as I only want to deal with 3D points
Code (glbasic) Select
TYPE TPoint
Loc[]
FUNCTION CreatePoint:x,y,z
self.Loc[0] = x
self.Loc[1] = y
self.Loc[2] = z
ENDFUNCTION
ENDTYPE

LOCAL P1 AS TPoint

But the compiler errors the "LOCAL P1 AS TPoint" line with (25) error : command not inside function or sub

MrTAToad

Odd - that example compiles fine here.

You do need to define the size of the array :

Code (glbasic) Select
TYPE TPoint
Loc[]
FUNCTION CreatePoint:x,y,z
DIM self.Loc[3]
self.Loc[0] = x
self.Loc[1] = y
self.Loc[2] = z
ENDFUNCTION
ENDTYPE

LOCAL P1 AS TPoint

Ruidesco

Yes, you can use any kind of variable inside a type, even variables of other types as well.
A different thing is initializing  those variables, since there is no default constructor/destructor for types because they are not objects; what I do to overcome that issue is defining an "init" function for my types which I call immediately after defining them, such as:
Code (glbasic) Select
LOCAL abc as MyType; abc.init()
In "init" is where I DIM arrays, for example.

matty47

I think I got to the bottom of my troubles. I had the following code in a file called Utils.gbas
Code (glbasic) Select
CONSTANT MaxDims=3

TYPE TPoint
Loc[]
FUNCTION init:x,y,z
DIM self.Loc[MaxDims]
self.Loc[0]=x
self.Loc[1]=y
self.Loc[2]=z
ENDFUNCTION
ENDTYPE


LOCAL P1 AS TPoint;P1.init(1,2,3)


with an empty main file called Test.gbas (Project Test). The compiler kept throwing an error on the creation of P1 (LOCAL P1.....line).
If I move this line to the main file I get no error. Therefore I assume that I can't declare variable of a type in an attached (referenced file) ??
Does that make sense?
Thanks for the help. I hope I can proceed now.
Matthew                     

Kitty Hello

The last line is an executed line - it must be inside a function. When moved to main.gbas, this is the "_MainGame" function that starts with the 1st line of the first file until the first FUNCTION/SUB is reached (or the 2nd file).