Friday, September 18, 2009

Implementing a custom loop

I love C#/C++/Java for loop, it let's you define the value by which you increment the loop variable
 for (int index = 0; index <= 1000; index += 2)
Delphi does not have an equal loop, you can use a while/repeat loop and implement something similar, anyways here's my trial Create a new VCL application, drop a button and a spin edit on the form, define a new type like so
type
  TurboLoopCallback = procedure (Index: Integer) of Object;
now the loop procedure
procedure TurboLoop(
  Index, (* loop start index *)
  ToIndex: Integer; (* until this value *)
  Callback: TurboLoopCallback; (* the callback procedure *)
  const Step: Integer = 2); (* the step value *)
begin
  (* is it a TO or DOWNTO loop? *)
  if Index > ToIndex then begin
    (* this is a DOWNTO loop
      for index := VALUE downto VALUE do... *)
    while Index >= ToIndex do begin
      (* callback procedure *)
      Callback(Index);
      (* decrement the value of index by STEP value *)
      Dec(Index, Step);
    end;
  end else begin
    (* this is a TO loop *)
    while Index <= ToIndex do begin
      (* callback procedure *)
      Callback(Index);
      (* increment the value of index by STEP value *)
      Inc(Index, Step);
    end;
  end;
  (* tadam! that's it *)
end;
add a new public procedure to form
...
  public
    procedure MessageLoop(Index: Integer);
  end;
...
it's implemention
procedure TForm1.MessageLoop(Index: Integer);
begin
  ShowMessageFmt('this is my %d message', [Index]);
end;
and finally on button's OnClick event write this code
procedure TForm1.Button1Click(Sender: TObject);
begin
  TurboLoop(1, 10, MessageLoop, seIndex.Value);
end;
This is just a proof of concept, it is not very productive,

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)