How can I use anonymous methods in Free Pascal?
Asked Answered
A

2

7

I tried to use Delphi's syntax for anonymous methods:

type
    fun = reference to function(): Integer;

Fpc shows a syntax error:

Error: Identifier not found "reference"

What's the Free Pascal equivalent to Delphi's anonymous methods, if any?

Aleron answered 17/10, 2011 at 20:19 Comment(1)
That's the most wanted feature of mine!Computerize
I
7

Anonymous methods are not implemented in FreePascal. The list of such features is here.

Inundate answered 17/10, 2011 at 20:38 Comment(6)
To this reading this in the future: greetings from 2011. Maybe this feature has been implemented in the meanwhile. Checking the list of features is probably a good idea indeed.Hex
@Wouter: Good point, but unnecessary, as David's post will have a datestamp on it within a few days.Alkaloid
It already has, even when it still looks like just a time. When you hover over it, you get the full timestamp...Spiel
Free Pascal 2.6 and 2.7.1 do support ISO style nested procedures, where you can pass nested procedures to external procedures without lowlevel shenigans, and they can access their parent's vars. (which is a form of state capture too). I also updated the status on the ansistring (codepage) feature.Mosher
@Marco I don't quite understand what you are saying here. The variable capture is just for the lifetime of the call to an external procedure, is that right? Is that what you are saying?Inundate
Yes, but the external procedure can also pass it on, iow that whole codepath. It must not be referenced after the original procedure returns though. It is not the same as anonymous methods (which capture is more dynamical), but it falls in the same category of functions, and some needs can be fulfilled by it, for passing custom code+data to general enumerator functions. Turbo Vision in Turbo times would really have benefited from it (TCollection.foreacH)Mosher
C
1

Anonymous methods are supported. Useful references:

The GitLab issue: https://gitlab.com/freepascal.org/fpc/source/-/issues/24481

The forum annoucement: https://forum.lazarus.freepascal.org/index.php?topic=59468.0

Finally, some examples given by Sven in the annoucement:

type
  TFunc = function: LongInt;
 
var
  p: TProcedure;
  f: TFunc;
  n: TNotifyEvent;
begin
  procedure(const aArg: String)
  begin
    Writeln(aArg);
  end('Hello World');
 
  p := procedure
       begin
             Writeln('Foobar');
           end;
  p();
 
  n := procedure(aSender: TObject);
       begin
             Writeln(HexStr(Pointer(aSender));
           end;
  n(Nil);
 
  f := function MyRes : LongInt;
       begin
             MyRes := 42;
           end;
  Writeln(f());
end.
Chaparro answered 27/1 at 2:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.