Software Call Backs?!

BlitzMax Forums/BlitzMax Beginners Area/Software Call Backs?!

MGE(Posted 2007) [#1]
TomToad graciously corrected my code, this is what the corrected code looks like:
Global FuncPointer()
'
SetFunctionPointer(Test)
FuncPointer()
'
Function SetFunctionPointer(Func())
 FuncPointer = Func
End Function
'
Function Test()
 Print "It worked!"
End Function


Basically it allows me to set a function pointer, which in turn gets called at the completion of a function. In a sense creating a dynamic call back ability. Is this THE way to do it or is there another way? This is working beautifully, but it's such an elegant and easy solution, it always makes me think ha..too easy, must be a hitch somewhere! :) lol...


TaskMaster(Posted 2007) [#2]
I would be careful using it as a callback.

If you use it as a callback, then the function calling it never ends until the function you called at the end ends. If you keep doing this and never let the functions end, then the stack will overflow.


MGE(Posted 2007) [#3]
ahh.. yes..very true, not a "real" call back. More like a hook into a function. And thanks for the heads up about the potential stack overflow. ;)


TomToad(Posted 2007) [#4]
Huh?
Any function that calls FuncPointer wil behave exactly the same as if it had called Test directly. The only difference is that FunctionPointer does not necessarily point to Test all the time. So for that reason, you need to be sure that FuncPointer points to a valid function. But that is true with any callback in any language, not just BlitzMAX.

Or do you mean that SetFunctionPointer function will not end simply because that's where FuncPointer is assigned? If that's what you mean, that is incorrect. He could've assigned the pointer outside the function just as easily with no difference, except eliminating the overhead caused by an extra function call.


Azathoth(Posted 2007) [#5]
I have no idea what TaskMaster is talking about.


TaskMaster(Posted 2007) [#6]
I am talking about him using it as a callback. Nothing to do with using a function pointer.


Azathoth(Posted 2007) [#7]
Still don't see the stack overflow, unless the callback is calling itself or the calling function which his example isn't doing.


Dreamora(Posted 2007) [#8]
BM has no callback functionality in that sense.
So you don't have any problems. It is just a function pointer to do some usefull stuff on interchangeable base.

The only a-linear thing BM offers are event hooks and even with those you are not able to break anything.


Grey Alien(Posted 2007) [#9]
Yeah I use simple function pointers like that a lot. It's a great way for users of my framework to add in their own error checking to say dialogs or to make their own action occur when an animation ends or a particle hits a location etc.