@Marc, Thaddy, thank you!
How can I know this without reading documentation for hours?
To insert source code, I clicked the symbol </> in the editor and this creates only two ticks.
And when I then view it in the preview I see a bunch of error messages.
Anyway, I believe it is too early to report errors about this feature because I would not find an end.
The problems are obvious if you compile or run nontrivial examples, which run without problems in Delphi.
I modified the source, so that it compiles
unchanged without problems in Delphi.
Compiler version is: Lazarus 2.3.0 (rev 0c96c0e3a5) FPC 3.3.1 x86_64-win64-win32/win64
I do however believe, this is a general problem not specific to windows. So more people should test this on other OS before reporting bugs. (I have no Linux currently) And I am almost 70 years old and retired so I will stay with windows, because I need it for my other stuff.
The following source code gives access violation at runtime in FPC.
If I modify the source and declare "f_outer" local, then it gives internal compiler error in FPC.
Both versions compile and run ok in Delphi.
program project1;
{$mode objfpc}{$H+}
{$modeswitch functionreferences}
{$modeswitch anonymousfunctions}
// {$warn 5036 off}// "Warning: (5036) Local variable "$Capturer" does not seem to be initialized"
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
Classes,Sysutils { you can add units after this };
type Tproc = reference to procedure;
Tfunc = reference to function(s:String):Tproc;
var p_inner: Tproc;
f_outer: Tfunc;
procedure caller;
begin
p_inner();
end;
procedure main;
var str: String;
// f_outer: Tfunc; // <----- doesnt compile when this is uncommented
begin
str := 'Hello World!';
f_outer := function(s:String):Tproc //This captures local and persistent copy of "str"
begin
Result := procedure // <----Access violation at runtime here in FPC, but not in Delphi. Program runs ok in Delphi.
begin
Writeln(s);
end;
Writeln('Outer function was called');
end;
p_inner := f_outer(str);
//This does NOT print the string "s"!
//it just instantiates the outer function and p_inner and captures their local context.
SetLength(str,0); //Erase the string content
Writeln('now calling p_inner');
caller(); //This line prints the string s="Hello World!", which was captured by the outer function.
//p_inner will be called from an external context, just for test and demonstration
end;
begin
main;
p_inner(); //calling p_inner again, when the context of main() is destroyed
readln;
end.