loopsanonymous-functiondelphi-xe5

In-place anonymous functions in Delphi loop


Is it possible to convert this:

program RangeLoop;

type
  TIndexedProc = reference to procedure(idx: Integer);

var
  i: Integer;
  p: TIndexedProc;

begin
  p := procedure(ix: Integer)
  var LocalVar: Integer;
  begin
    //Do some processing
  end;
  for i in [2..7] do p(i);
end.

into something like this:

program RangeLoop;

var
  i: Integer;

begin
  for i in [2..7] do procedure(ix: Integer)
  var LocalVar: Boolean;
  begin
    //Do some processing
  end;
end.

?

I know that the last code block is invalid.


Solution

  • In Delphi 10.3 and later, you can use an inline variable inside the loop to hold the anonymous procedure, eg:

    program RangeLoop;
    
    var
      i: Integer;
    
    begin
      for i in [2..7] do
      begin
        var p := procedure(ix: Integer)
        begin
          //Do some processing
          var LocalVar := ...;
        end;
        p(i);
      end;
    end.
    

    Prior to 10.3, what you are asking for is simply not doable the way you want. Defining p above the loop is your best choice, unless you use a standalone procedure, eg:

    program RangeLoop;
    
    procedure p(ix: Integer);
    var
      LocalVar: Integer;
    begin
      //Do some processing
    end;
    
    var
      i: Integer;
    
    begin
      for i in [2..7] do p(i);
    end.
    

    Or, if you can use TParallel.For() instead, if your loop iterations are thread-safe and not dependent on each other's results:

    program RangeLoop;
    
    uses
      System.Threading;
    
    begin
      TParallel.For(2, 7, procedure(ix: Integer)
        begin
          //Do some processing
        end;
      );
    end.