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
  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 *)
  (* 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 *)
      (* decrement the value of index by STEP value *)
      Dec(Index, Step);
  end else begin
    (* this is a TO loop *)
    while Index <= ToIndex do begin
      (* callback procedure *)
      (* increment the value of index by STEP value *)
      Inc(Index, Step);
  (* tadam! that's it *)
add a new public procedure to form
    procedure MessageLoop(Index: Integer);
it's implemention
procedure TForm1.MessageLoop(Index: Integer);
  ShowMessageFmt('this is my %d message', [Index]);
and finally on button's OnClick event write this code
procedure TForm1.Button1Click(Sender: TObject);
  TurboLoop(1, 10, MessageLoop, seIndex.Value);
This is just a proof of concept, it is not very productive,

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)