Forum > FPC development
Enumerator pass direct reference via for x in statement
(1/1)
stefc:
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:
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:
--- Quote from: howardpc 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.
--- End quote ---
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 ;)
Navigation
[0] Message Index