Compare messes up lists??

BlitzMax Forums/BlitzMax Beginners Area/Compare messes up lists??

therevills(Posted 2008) [#1]
Hi All,

Ive got a type called TSettler which is in a list TSettlerList.

I add a new settler to the list by:

Type TSettlersList Extends TList
	Method AddNew:TSettler(x:Int, y:Int, image:TGameImage, what:String)
		Local s:TSettler = TSettler.Create(image, x, y)
		s.settlers = Self 'point to this list	
		s.what = what
		s.setUpIdleAnimation()
		AddLast(s)
		Return s
	End Method


And in TSettler I have got this bit of code:

Method Compare:Int(other:Object)
  	Return y - TSettler(other).y
End Method


Which helps the z-ordering when drawing the settlers on screen... but now when I want to remove a settler from the list it removes the wrong one!?!?!

Method Kill()
   If settlers <> Null Then 
       settlers.Remove(Self)
       settlers = Null 'prevent circular reference
   EndIf
End Method


Any ideas?

Thanks!


GfK(Posted 2008) [#2]
The compare method, afaik, should only return -1, 0, or 1.


therevills(Posted 2008) [#3]
Cheers Gfk... well the return type for the method is an int...

Here is some runnable code from my other post, Ive added TPersonList and TPerson.

Click on the buildings (white squares) to fill up all the slots (green ovals) with people (yellow squares)... then click on the people to remove/delete them (start with the people to the right-hand side of the houses)... try this with and without the compare method....



Does anyone know how to fix this?


Otus(Posted 2008) [#4]
No, compare:
Returns a value less than 0 if an object is less than another object, a value greater than 0 if an object is greater than another object or the value 0 if an object equals another object.


However, with your code, if two TSettlers have the same y they are treated as the same. You should use something like:
Method Compare:Int(other:Object)
  	Local s:TSettler = TSettler(other)
  	If y = s.y Return Super.Compare(other)
  	Return y - s.y
End Method



therevills(Posted 2008) [#5]
THANK YOU!!!!

Just tested with my example code... and works great!

Ive spent most of the day tracking down this problem (finally noticed it was the compare method), but didnt know what was wrong!

Thanks again!

What does super.compare perform?