Global array in type

BlitzMax Forums/BlitzMax Beginners Area/Global array in type

this doesnt work. what do I do?
Type t
	Global a[2]
EndType


Don't size the array and create a new method that do this for you.

Type t
	Global a:Int[]
	Method New()
		a=a[..10]  ' Slice array to 10 elements (Dim)
	End Method
End Type


n:t=New t
n.a[0]=10
Print n.a[0]  ' Result 10
Print SizeOf t.a  ' Result 40 (4*10)


j:t=New t
Print j.a[0]  ' Result 10


I just want one array always. I will only access it with t.a[

This is a good question. Surely you must be able to create a global array in a type?

Extron, in your example if you created 2 instances of the 't' type, when creating the second instance wouldn't you wipe the contents of the array?

I get this error BTW:

Compile Error
Type global initializers must be constant

Hmmm. It's strange that you can't do what you want to do, but I can't really think of a situation where you'd need to. :/

According to the documentation, globals and consts are not instance variables (like Fields are), and so are available simply by saying :

print t.a

*without* first creating an instance of the type.

Extron's example is confusing, since every time you create a new instance of "t" you will in effect be changing every reference to the array "a" everywhere "t" is used, regardless whether one creates an instance of it or accesses the array directly.

Fun, fun, fun :-)

In case it's confusing you can do this. ;)

Type t
	Global a:Int[]
	Function SizeArray()
		a=a[..10]
	End function
End Type


t.SizeArray()
n:t=New t
n.a[0]=10
Print n.a[0]  ' Result 10
Print SizeOf t.a  ' Result 40 (4*10)


j:t=New t
Print j.a[0]  ' Result 10


t.SizeArray() initiate the array for you.

Hi Extron,

I understand your example. But do you know the reasoning for not being able to create a static array in a type as in Coorae's example?

Saying that, you have shown a work around, I just though it was odd you can't declare a static array.

Surely, its a bug? It says "Error:Type global initializers must be constant" - well it is a constant.

A bug, maybe.

An array in BlitzMAX is an object, perhaps this is the problem?

It seems like you can do something like this....

Type poo
Global b[]
Method New()
b = New Int[2]
b[0]=100
b[1]=200
End Method
End Type


a:poo = New poo
b:poo = New poo

Print a.b[0]
Print a.b[1]


Print b.b[0]
Print b.b[1]

Aaron

thanks, I guess this is the workaround
Type t
	Global a[]
EndType
t.a=New Int[2]

That is what I will use

No, put it in the constructor of the Type. Much better place.

Aaron

that would create a new array every time it makes a new instance. I just want 1 array

Just Stick a Null check around it
Method New()
If b = Null
b = New Int[2]
b[0] = 23
b[1] = 45
Print "Alloced!"
EndIf
End Method

Aaron

actually I need to use the array before I create any instances lol

Simple then:
Type t
	Global a[]
EndType

t.a = New Int[2]