Recent

Author Topic: Enumerator pass direct reference via for x in statement  (Read 3460 times)

stefc

  • Newbie
  • Posts: 2
Enumerator pass direct reference via for x in statement
« on: January 09, 2015, 08:21:38 am »
I have written a enumerator class for a Polygon record that yields the edges.
<code>
type
   THexagonEnumerator = class(TPolygonEnumerator)
   private
      fPolygon: THexagon;
      fCurrent: Integer;
   protected
      function GetCurrent: TLine; override;
   public
      constructor Create(const aPolygon: THexagon);
      function MoveNext: Boolean; override;
   end;


constructor THexagonEnumerator.Create(const aPolygon: THexagon);
begin
   inherited Create;
   fPolygon := aPolygon;
   fCurrent := -1;
end;

function THexagonEnumerator.MoveNext: Boolean;
begin
   Inc(fCurrent);
   Result := FCurrent <= 5;
end;

function THexagonEnumerator.GetCurrent: TLine;
begin
   Result := Line(
      fPolygon[fCurrent].x,
      fPolygon[fCurrent].y,
      fPolygon[(fCurrent+1) mod 6].x,
      fPolygon[(fCurrent+1) mod 6].y);
end;

operator Enumerator(const aHexagon: THexagon): TPolygonEnumerator;
begin
   Result := THexagonEnumerator.Create(aHexagon);
end;
</code>

Now I can fine use it via :

var
   polygon: THexagon;
   edge: TLine;
begin
   polygon := Hexagon(18,15);
   for edge in polygon do
     ...

What I needed is that I can create the TPolygonEnumerator myself, so I can use different enumerator's for the same Type.

var
   enumerator : TPolygonEnumerator;
   edge : TLine;

  for edge in TPolygonEnumerator.Create(Hexagon(x,y)) do

How can I do such stuff ? It seems to me that the compiler not expected a direct reference of a Enumerator class

Stefc



howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: Enumerator pass direct reference via for x in statement
« Reply #1 on: January 09, 2015, 09:23:44 am »
If you use a TFPList to store your data, it has enumerator support built in.
You simply need to call GetEnumerator to have Current and MoveNext methods.

stefc

  • Newbie
  • Posts: 2
Re: Enumerator pass direct reference via for x in statement
« Reply #2 on: January 09, 2015, 09:33:27 am »
If you use a TFPList to store your data, it has enumerator support built in.
You simply need to call GetEnumerator to have Current and MoveNext methods.

The Type on which I iterate is defined as a simple array :

   PHexagon = ^THexagon;
   THexagon = array[0..5] of TPoint;

in my case I don't use much of the internal classes ;)

 

TinyPortal © 2005-2018