Returning an Object and Converting To Type

BlitzMax Forums/BlitzMax Programming/Returning an Object and Converting To Type

Hardcoal(Posted 2014) [#1]
im trying to get an answer from a function that returns an object.
but after returning a general object I want to convert it to a specific type.
is it clear what im trying?

		function ListGetByNum:Object(List:TList, Number = 1)
			Local Obj:Object, Counter
			For Obj = EachIn List
				Counter = Counter + 1
				If Counter = Number Then Return Obj
			Next
		End function

Ship:Typ_Ship

Ship=ListGetByNum(ShipsList,1)



Since the function returns an object how can I translate the answer to
Typ_ship?

Generaly.. how can I read from a list beside going threw all the list using Eachin..?


Yasha(Posted 2014) [#2]
You can use the built-in ValueAtIndex method on TList for this. If you're accessing via a lot of different indices in one go, you may find it handy to convert the list to an array first, with the ToArray method. If you're accessing by index very often (every frame or more) and only adding objects very occasionally (like once when the collection is built), you should probably be using an array in preference to a list. (There is no good way to read from the middle of a list: they're intended for quickly pushing/popping things at either end and for iterating over the whole thing to do something to each element. For other usage patterns, try an array or map.)

To convert the actual element to a more specific type, use a cast:

Ship = Typ_Ship(ShipsList.ValueAtIndex(1))


Any type name can be "called" like a function to try to convert its argument to a value of that type. If it fails to convert the value (because it's not of that type after all), it returns Null instead.

Note that another advantage of using arrays is that they can be more strongly typed, so you don't need to bother with casts unless the array contains objects of multiple subtypes.


Hardcoal(Posted 2014) [#3]
thanks yasha! up till now i didnt even know how to read list properly.
omg.


Hardcoal(Posted 2014) [#4]
The problem with blitsmax online manual is that you think
The language commands are what appears there sums it up.
Where in reality there is much more under the surface sort of speak.

Blitzmax as for it self is a treasure hunting 'game'
Every time i find somthing new i feel like i found a treasure chest.


Henri(Posted 2014) [#5]
Yes, it's a bit like that:-) .Might be due to a fact that Blitzmax is a crossover between C and basic. Basic-part is obvious and C-part is little under the hood.

-Henri


Wiebo(Posted 2014) [#6]
Some command docs are OOP based, while others are not. It always is interesting to check out the source of a module to see what kind of methods are available. Not the most efficient way of doing things, but definitely recommmended.