Referencing Functions

BlitzMax Forums/BlitzMax Programming/Referencing Functions

William Drescher(Posted 2009) [#1]
So is there any way to do this:

Function FuncNumber1()
    Print "Hello World"
End Function

Global FuncNumber2() = Ptr(FuncNumber)

FunctionNumber2()    ' Prints "Hello World"


Or is there something similar to that? I remember when I used to code calculator apps in TIBasic you could use the # symbol to point the program to a function that was stored in a string variable which is kind of similar to what I'm showing above.


TaskMaster(Posted 2009) [#2]
Global FuncNumber2()

FuncNumber2 = FuncNumber1


William Drescher(Posted 2009) [#3]
When I did that I got an error that said FuncNumber2 was not a function that could be called.


Czar Flavius(Posted 2009) [#4]
This works for me

SuperStrict
Global FuncNumber2()

FuncNumber2 = FuncNumber1 

FuncNumber2()

Function FuncNumber1()
	Print "Hi"
End Function



Evil Roy Ferguson(Posted 2009) [#5]
If your function has a return value or accepts parameters, the syntax becomes:

Local funcPtr:ReturnType(param1:Type1, param2:Type2)


etc. -- it won't work unless these are specified.

It's fun to use them as function parameters :P

SuperStrict

' A function we'll take the address of later
Function RepeatString1:String(str:String, times:Int)
	Local parts:String[] = New String[times]		
	For Local i:Int = 0 Until times
		parts[i] = str
	Next
	
	Return "".Join(parts)
End Function

' A function we'll take the address of later
Function RepeatString2:String(str:String, times:Int)
	Local result:String	
	For Local i:Int = 0 Until times
		result :+ str
	Next
	
	Return result
End Function

' This is the function that takes a function as a parameter
Function TimeRepeatString:Int(func:String(str:String, times:Int), testTimes:Int = 1000, stringRepetitions:Int = 100)
	Local startTime:Int = MilliSecs()

	Local str:String = "hello"
		
	For Local i:Int = 0 Until testTimes
		func(str, stringRepetitions)
	Next
	
	Return MilliSecs() - startTime
End Function

' Example of passing in references
Print TimeRepeatString(RepeatString1)
Print TimeRepeatString(RepeatString2)



N(Posted 2009) [#6]
It's fun to use them as function parameters :P


Method PreInit:LuGIInitFunction(cb(vm:Byte Ptr, rfield(off%, typ%, name$, clas@ Ptr), rmethod(fn:Int(state@ Ptr), name$, clas@ Ptr)), requiresState%=True)



Evil Roy Ferguson(Posted 2009) [#7]
I don't believe my statement has been invalidated.


N(Posted 2009) [#8]
No, if anything, I've cemented it. A method that takes a callback that takes a callback that takes a callback is a beautiful thing.