PDA

View Full Version : TList and object removing



Darkhog
26-06-2013, 07:07 PM
I'm going to handle collisions for sprites using TLists. One for bad guys, one for enemy bullets and one for destructible objects and one for player bullets. But I have issue with understanding how deletion of objects from TList works.

If I want to delete object (with freeing memory), I need to do:


MyList.Items[4].Destroy; //let's say object we want to delete has index of 4
MyList.Delete(4);

right?

SilverWarior
27-06-2013, 12:13 AM
TList does not alow direct freein of object as it serves only as colection of pointers to objects.

If you want to automaticly free up object upon their removal from list then I suggest to use TObjectList instead.
When TObjectList is created using

ObjectList := TObjectList.Create(True)
it means that TObjectList owns the objects added to it and automatically destroys them upon removal or on destroy of the whole TObjectList.

Darkhog
27-06-2013, 08:29 AM
Yeah, but from what I see, it can't remove items with specific index. Which defies my purpose of having many TSprite instances and remove only specific ones.

Dan
27-06-2013, 08:35 AM
TObject(MyList.Items[4]).Free;
MyList.Delete(4);

laggyluk
27-06-2013, 09:35 AM
btw if you gonna iterate over list and remove elements in the process then better start from the end and do 'downto' or indexes will mess up

also you might wanna check out generic collections that allow you to create TList<TSprite>
in delphi its generics.collections unit and in lazarus fgl unit

Darkhog
29-06-2013, 10:33 PM
btw if you gonna iterate over list and remove elements in the process then better start from the end and do 'downto' or indexes will mess up

Of course. I've thought that was no-brainer. Also didn't know that Freepascal has generic collections, thought it was only java/c# thing. Nice to know.