An array containing a type

BlitzMax Forums/BlitzMax Beginners Area/An array containing a type

hi, here are some tips:

Strict

Type Tplayer
	Global PlayerArray:Tplayer[]
	
	Field name:String
	Field x:Float
	Field y:Float
	
	Function AddPlayer:Tplayer(pname:String ,xpos:Float , ypos:Float)
		Local p = Len(Tplayer.PlayerArray)						' get the current number of elements in the array
		Tplayer.PlayerArray = Tplayer.PlayerArray[..p+1]		' Slice to resize the array
		Local temp:Tplayer = New Tplayer					' create a player and assign attributes
			temp.name = pname
			temp.x = xpos
			temp.y = ypos
		
		Tplayer.PlayerArray[p] = temp						' add the newly created player to the array
		Return temp	' return a reference to the newly crreated object (there if you need it)
	End Function 
	
	
End Type


Tplayer.AddPlayer("Charlie" ,100,200)
Tplayer.AddPlayer("Brenda" ,20,20)
	
	
Print Tplayer.PlayerArray[0].name

Print Tplayer.PlayerArray[1].name



First, you can Encapsulate the array within the Tplayer Type. This is called a Static Field

Type Tplayer
	Global PlayerArray:Tplayer[]


second, you can use a Constructor to help initialize the fields and add the Object to the list

Function AddPlayer:Tplayer(pname:String ,xpos:Float , ypos:Float)
		Local p = Len(Tplayer.PlayerArray)						' get the current number of elements in the array
		Tplayer.PlayerArray = Tplayer.PlayerArray[..p+1]		' Slice to resize the array
		Local temp:Tplayer = New Tplayer					' create a player and assign attributes
			temp.name = pname
			temp.x = xpos
			temp.y = ypos
		
		Tplayer.PlayerArray[p] = temp						' add the newly created player to the array
		Return temp	' return a reference to the newly crreated object (there if you need it)
	End Function 


Third, Instead of creating an array of a fixed size, you can slice it whenever you need to add a new player.

Tplayer.PlayerArray = Tplayer.PlayerArray[..p+1]		' Slice to resize the array