Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass Functions as Parameters in Procedures in Delphi?

Is it possible to pass an object function as a parameter in a procedure rather than passing the whole object?

I have a record definition with a function defined as a public class parameter such as:

    TMyRecord = record
      public
        class function New(const a, b: Integer): TMyRecord; static;
        function GiveMeAValue(inputValue: integer): Single;
      public
        a, b: Integer;
      end;

The function could be something like:

    function TMyRecord.GiveMeAValue(inputValue: Integer): Single;
    begin
      RESULT := inputValue/(self.a + self.b);
    end;

I then wish to define a procedure that calls on the class function GiveMeAValue but I don't want to pass it the whole record. Can I do something like this, for example:

    Procedure DoSomething(var1: Single; var2, var3: Integer, ?TMyRecord.GiveMeAValue?);
    begin
      var1 = ?TMyRecord.GiveMeAValue?(var2 + var3);
      //Do Some Other Stuff
    end;

If so then how would I correctly pass the function as a procedure parameter?

like image 585
Trojanian Avatar asked Nov 05 '13 22:11

Trojanian


People also ask

How do you pass a Func as a parameter?

Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.

How do you call a function in Delphi?

You can make the call using the declared name of the routine (with or without qualifiers) or using a procedural variable that points to the routine. In either case, if the routine is declared with parameters, your call to it must pass parameters that correspond in order and type to the parameter list of the routine.

What are the two ways of passing parameters to a procedure?

1C:Enterprise script supports two methods of passing parameters to procedures and functions: by reference and by value.

Can a function be a parameter in another function?

Functions can be passed into other functions Functions, like any other object, can be passed as an argument to another function.


1 Answers

You can define a new type for the function like

TGiveMeAValue= function(inputValue: integer): Single of object;// this definition works fine for methods for records.

then define the method DoSomething

Procedure DoSomething(var1: Single; var2, var3: Integer;GiveMeAValue: TGiveMeAValue);
begin
  writeln(GiveMeAValue(var2 + var3));
end;

And use like so

var
  L : TMyRecord;
begin
    l.a:=4;
    l.b:=1;
    DoSomething(1, 20, 5, L.GiveMeAValue);
end;
like image 81
RRUZ Avatar answered Sep 24 '22 17:09

RRUZ