function myfunc(var:unknown?)

BlitzMax Forums/BlitzMax Programming/function myfunc(var:unknown?)

Snixx(Posted 2010) [#1]
How can I pass a variable of any type (string, int, float, etc) to a function without having it set in stone and have it automagically "detected" as a float or whatever?


plash(Posted 2010) [#2]
Not possible.
You can only do this with objects; data types are not objects.


Dreamora(Posted 2010) [#3]
strings are objects indeed.
As such you can pass them all in as objects, just cast the numerics to strings or do what many others do: Add boxing / unboxing (with numeric wrapper classes)


Czar Flavius(Posted 2010) [#4]
Type TInt
	Field value:Int
	
	Function Create:TInt(v:Int)
		Local my_tint:TInt = New TInt
		my_tint.value = v
		Return my_tint
	End Function
End Type
'create similar types for float etc

Function generic_var(parameter:Object)
	If TInt(parameter)
		Local i:Int = TInt(parameter).value
	'ElseIf TFloat(parameter)
		'
	EndIf
End Function

Local i:TInt = TInt.Create(5)
generic_var(i)


A less efficient, but perhaps simpler way
Const as_int = 0, as_float = 1, as_string = 2
Function generic_var(var_type:Int, parameter:String)
	Select var_type
		Case as_int
			Local i:Int = Int(parameter)
			'...
		Case as_float
			Local f:Float = Float(parameter)
			'...
		Case as_string
			Local s:String = String(parameter)
			'...
	End Select
End Function


generic_var(as_float, "5.3")