Page 1 of 1

How to store and use a callback function (kind of delegate)

Posted: Tue Feb 06, 2024 10:44 am
by Alessandro777
Hello,

I wish to create a structure where I can store a point to a function, and call it when needed.
Example:

Code: Select all

Structure TCalc
	*addFunction
endstructure

procedure add(n1, n2)
	procedurereturn (n1+n2)
endprocedure

theCalc.TCalc

theCalc\addFunction = @add()

;; FUNCTION CALL!

theCalc\addFunction(5, 4)
Is it possible to do this in SpiderBasic? How?

Thank you!

Re: How to store and use a callback function (kind of delegate)

Posted: Tue Feb 06, 2024 11:39 am
by Peter
Perhaps as in the following example:

Code: Select all

Procedure CallFunction(Function, Param1, Param2)
  
  Protected ReturnValue
  
  ! if (typeof v_function === "function") { 
  !   v_returnvalue = v_function(v_param1, v_param2);
  ! }
  
  ProcedureReturn ReturnValue
  
EndProcedure


Structure TCalc
  *addFunction
EndStructure

Procedure add(n1, n2)
  ProcedureReturn (n1+n2)
EndProcedure

theCalc.TCalc

theCalc\addFunction = @add()

Debug CallFunction(theCalc\addFunction, 1, 2)
Of course it would be better if you could pass a parameter array to CallFunction() (like in PureBasic), so that the function would be more flexible. Maybe someone knows a solution.

Re: How to store and use a callback function (kind of delegate)

Posted: Wed Feb 07, 2024 12:54 pm
by the.weavster
An alternative methodology to think about :?: ...

Code: Select all

; Interface describes the methods of our object
Interface MyWidget
  add.d(n1.d, n2.d)
  getText.s()
  setText(msg.s)
  destroy()
EndInterface

; Implement the members and create an instance
Procedure.i New_MyWidget()
  EnableJS
  var obj = {};
  obj.myText = "";
  obj._vt = {};
  obj._vt._add = function(self, n1, n2) { return n1 + n2; };
  obj._vt._getText = function(self) { return self.myText; };
  obj._vt._setText = function(self, msg) { self.myText = msg; };
  obj._vt._destroy = function(self) { delete self; return null; };
  return obj;
  DisableJS
EndProcedure

; To pass an object to a procedure
Procedure LookAtThat(x.MyWidget)
  Debug x\getText()
EndProcedure

; And give it a try
widget.MyWidget = New_MyWidget()
Debug widget\add(2.5, 1.7)
widget\setText("Hello, World!")
LookAtThat(widget)
widget\destroy()

Re: How to store and use a callback function (kind of delegate)

Posted: Wed Feb 07, 2024 2:07 pm
by Alessandro777
Thank you these workarounds. I think they are interesting (I learnt a lot!) but are not so easy from maintenance and upgrade point of view.
I think SpiderBasic would need a datatype to manage procedures" (as the datatype "window" for example).
So...

Code: Select all

structure TTest
    myFunc.procedure
endstructure

OR...
structure TTest
    *myFunc.procedure
endstructure

test1.TTest

procedure myFunc()
    bla bla bla.....
endprocedure

test1.myFunc = @myFunc