[fpc-pascal] Re: Delphi's anonymous functions in Free Pascal

Sven Barth pascaldragon at googlemail.com
Wed Oct 19 10:16:09 CEST 2011


Am 19.10.2011 09:31, schrieb Michael Fuchs:
> I would prefer a style like
>
> myfunc := @function(x, y: Integer): Integer Result := x + y;

And how would you create more complex functions? In Pascal code blocks 
are started with "begin" and ended with "end". I don't see a reason why 
anonymous methods should differ here.

Also the example given by Embarcadero is a bit boring. The interesting 
thing about anonymous methods (and nested functions types in FPC) is 
that they can access variables of the surrounding function (at least I 
hope that I've understand it correctly that nested function types can do 
that).

E.g.

TIntegerFunc = reference to function: Integer;

procedure SomeOtherProc(aFunc: TIntegerFunc);
...

procedure Foo;
var
   x: Integer;
begin
   x := 42;
   SomeOtherProc(function: Integer; begin Result := x; end;);
end;

I haven't tested that, but from the description that should work.

The FPC equivalent should be (not tested as well):

type
   TIntegerFunc = function: Integer is nested;

procedure SomeOtherProc(aFunc: TIntegerFunc);
...

procedure Foo;
var
   x: Integer;

   function ReturnX: Integer;
   begin
     Result := x;
   end;

begin
   x := 42;
   SomeOtherProc(@ReturnX);
end;

Regards,
Sven



More information about the fpc-pascal mailing list