Primitives in TMaps

BlitzMax Forums/BlitzMax Programming/Primitives in TMaps

Macguffin(Posted 2008) [#1]
This probably has an easy answer, but I'm having a tough time finding it.

TMap uses key:object and value:object. If you want your value to be a primitive like an int, what's the easiest way to go about converting it? I could put it in as a string and then cast it when using it, but that seemed kinda kludgey.

Thanks.


plash(Posted 2008) [#2]
(to remove the possible overhead with a string object)
Type TInt
Field Value:int
End Type

Or use a string.. there is no other way.


Beaker(Posted 2008) [#3]
You could always copy the code from the TMap module and adapt it to use Ints.


Macguffin(Posted 2008) [#4]
Ok - thanks, guys. I just wanted to be sure there wasn't some ridiculously simple way I was just missing. I'll tinker with it.


Czar Flavius(Posted 2008) [#5]
You could look at the TMap code and copy it and change object to int.


Azathoth(Posted 2008) [#6]
You could use a single element array to store the primitive in.


plash(Posted 2008) [#7]
How would you add the array to the TMap? Its type will still be an integer.


Dreamora(Posted 2008) [#8]
no not really. All array extend from the Class Array -> IntArray, FloatArray etc.
Otherwise you couldn't slice them as that is a capability of that class not some magical memory hacking.


Azathoth(Posted 2008) [#9]
How would you add the array to the TMap? Its type will still be an integer.
Arrays are objects. You could simply do:
MapInsert( map,key,[1])


TomToad(Posted 2008) [#10]
At first it seems that Azathoth's idea wouldn't work, but after much fiddling, I finally got an example to work.
SuperStrict

Local map:TMap = CreateMap() 'create the map
Local i:Int 'Used as the index in loops
Local Value:Int 'An Int variable to show that the result is actually an Int and not an object

For i = 0 To 10 'fill the map with values 0-10 using keys "Key0" - "Key10"
	MapInsert(Map,"Key"+i,[i]) 'Save i as a single element array
Next

For i = 0 To 10 'Read the given keys "Key0' - "Key10"
	Value = Int[](MapValueForKey(Map,"Key"+i))[0] 'Cast the object to an Int array, and access element 0
	Print Value 'print the result
Next



JoshK(Posted 2008) [#11]
You have to have a sort method. Otherwise it won't know that 1=1.

Type TInt
Field Value:int

Method Compare:Int(o:Object)
if TInt(o)>value return 1
if TInt(o)<value return -1
return 0
EndMethod

End Type