Author: Tomas Rutkauskas
Is there some way I can store a procedure or function in a variable so I can call
the procedure with the variable? I'm thinking of something similar to where you can
declare a variable of a certain object type, then assign different objects of that
type to the variable. If it can be done with procedures, how would it be assigned
and what would the syntax be to call the procedure?
Answer:
Yes, you can declare a procedural type for functions with the same parameter list
and function type. Briefly it looks something like this:
1 { ... }2 type3 TMathFunc = function(A, B: double): double; {defines signature of function}4 { ... }5 var6 mathfunc: TMathFunc;
7 answer: double;
8 { ... }9 10 {Now if you define two functions}11 12 function Adder(A, B: double): double;
13 begin14 result := A + B;
15 end;
16 17 function Multiplier(A, B: double): double;
18 begin19 result := A * B;
20 end;
21 22 begin23 {You can do this}24 mathfunc := Adder;
25 answer := mathfunc(5, 9);
26 mathfunc := Multiplier;
27 answer := mathfunc(5, 9);
28 end;