Counting certain types in a single list
BlitzMax Forums/BlitzMax Beginners Area/Counting certain types in a single list
| ||
Hi, I`m trying to use this single function to count multiple types in a global list.Function Count:Int() Local Count:Int Count=CountList(List) Return Count End Function For example, I want to be able to pass the parameter TPlayer and have it return only the amount of TPlayers contained in the global list. Can someone please show me how this can be achieved as I`m having a little difficulty with it. Thanks for any help, Jason. |
| ||
One design might be to have a CountList function on each Type you want to use this on :Type TPlayer Function CountList:int(list:TList) Local count:int For Local obj:TPlayer = eachin list count:+ 1 Next return count End Function End Type But there are all kinds of ways you can do this kind of thing. For example, you might extend TList and add extra functionality to AddLast/First etc to keep a separate count of individual types. Or use a TMap instead of a list, with entries in the map containing lists of the individual types. It all depends what the rest of your design is like. |
| ||
If you can do it like Brucey suggested, you probably should. If you don't know the types in advance, or there are too many, you can use reflection:Function Count%(list:TList, id:TTypeId) Local cnt% For Local o:Object = EachIn list If TTypeId.ForObject(o).ExtendsType(id) Then cnt :+ 1 Next Return cnt End Function Print Count( list, TTypeId.ForName("TPlayer") ) |
| ||
Any idea how much overhead using reflection adds? |
| ||
Thanks for the advice. I had originally created a CountList() function inside each type. I was just trying to see if I could simply use the one inside the base type that the others were extended from. Jason. |
| ||
What I usually do is have a main TList with my objects and a TMap with TLists in it as well, but only containing type specific objects. That way you can quickly access, or search for a specific object without too much overhead. As searching in a dedicated TList is of course a lot faster than in one big TList, containing all game objects. The number of iterations should usually be lower on the dedicated list, depending on how many different objects you have of course. |
| ||
You can have a Int flag inside the base type that is set depending on the extended type and just count up when the flag you are looking for is found, or just try a typecast and see if the result is null or non-null, or keep separate lists :-) |
| ||
Thanks for the selection of different ideas all :) Jason. |
| ||
Any idea how much overhead using reflection adds? I'm not sure if that was rhetorical, but it's slower by a factor of ten in this case using ExtendsType, as I wrote above. That might be too slow, but you can work around it: Output: 2181 2087 |
| ||
I'm not sure if that was rhetorical No, but I thought you might think so :-) Ah. bbObjectDowncast. Intriguing ! |