How to use SortList for your own types

BlitzMax Forums/BlitzMax Tutorials/How to use SortList for your own types

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

So you thought that SortList could only be used for integers and strings? Wrong! You can order any type with it. All you need to do is implement/override the Compare method within your type. When compared with another object, you just return whether it is "less than", "greater than" or "equal to" the other object, with a number less than, greater than, or equal to zero.

See this example code:
Type sprite
	Field order
	
	Method Compare(otherObject:Object)
		s:sprite = sprite(otherObject)
		If Not s Then Return 1			' Object not a sprite: define greater than any sprite
		Return order - s.order
	End Method
End Type

' ----------------------------

SeedRnd MilliSecs()
sprite_list:TList = New TList

' Create a list of randomised sprites
For i=1 To 100
	s:sprite = New sprite
	s.order = Rand(100)
	ListAddLast sprite_list, s
Next

' Make sure it doesn't fall over if something odd is added
ListAddLast sprite_list, "Object that is not a sprite"

' Sort the list!
SortList sprite_list

' Check to see if it is sorted correctly
For s = EachIn sprite_list
	Print s.order
Next


We need to implement the Compare method because that is what the SortList command uses. We are sorting the sprites in order of the "order" field in the sprite type.

Try running the code - the sprites are now ordered correctly!