SRL Archive - Delphi/FPC Help and Tutorials

Function as parameter?


edfromhumanresources

2011-04-22 12:50:49

In C you can use a pointer to a function as a parameter in another function like so:

void MyFunction( void (*ParameterFunction)(ParameterFunctionsParameters) ) {
}

Is this possible in pascal?

Echo_

2011-04-22 13:21:35

I'm pretty sure you can do it in pascal considering you can do it in Simba scripts. Here is a commonly used example:

  MMouse(x, y, RandomRange(-2, 2), RandomRange(-2, 2)); 

So it will use the return value of the RandomRange function for the pixel randomness of x and y. You just have to make sure that the function you are using as the parameter returns the data type needed.

Sex

2011-04-22 14:00:51

function TestFunc : string;
begin
result := 'test';
end;

procedure Test(Func : function : string);
begin
Writeln(Func());
end;

begin
Test(@TestFunc);
end.
or
function TestFunc : string;
begin
result := 'test';
end;

procedure Test(Func : string; Params : TVariantArray);
begin
writeln(CallProc('TestFunc', Params));
end;

begin
Test('TestFunc', []);
end.
:)

Dgby714

2011-04-22 15:47:02

If you would like to pass parameters!

type
TExFunc = function(s: string): boolean;

function test(test2: TExFunc): boolean;

Sex

2011-04-22 16:03:00

From: Dgby714
If you would like to pass parameters!

Simba Code:
[LEFT]type
TExFunc = function(s: string): boolean;

function test(test2: TExFunc): boolean;
[/LEFT]

Or you can use CallProc :p.

Dgby714

2011-04-22 16:05:01

From: Sex
Or you can use CallProc :p.


Yes but using CallProc requires you to make wrappers for Simba's functions.

Sex

2011-04-22 16:07:32

Yeah, was gonna just edit that in…but I still think it is nifty :).