Delphi array initialization

Alex O picture Alex O · Feb 20, 2010 · Viewed 30k times · Source

I currently have this, and it sucks:

type TpointArray = array [0..3] of Tpoint;

class function rotationTable.offsets(pType, rotState, dir: integer): TpointArray;
begin

  Result[0] := point(1, 1);
  Result[1] := point(1, 2);
  Result[2] := point(1, 1);
  Result[3] := point(1, 1);
end;

but instead, i want to do something like this:

class function rotationTable.offsets(pType, rotState, dir: integer): TpointArray;
begin
   Result := [Point(1,1), Point(1,2), Point(1,1), Point(1,1)];
end;

However, on compilation, it complains that the [1, 2, 3, 4] syntax can only work for Integers.

Is there a way to instantiate/initialize an array of Tpoint similar to the way that i want?

Answer

Gerry Coll picture Gerry Coll · Feb 20, 2010

Arrays of records can be intialised in const expressions:

const
  Points : TPointArray = ((X: 1; Y: 1), (X:1; Y:2), (X:1; Y:1), (X:1; Y:1));

class function rotationTable.offsets(pType, rotState, dir: integer): TpointArray;
begin
   Result := Points;
end;

In XE7 it is possible to fill a dynamic array of records like this:

function GetPointArray: TArray<TPoint>;
begin
  Result := [Point(1,1),Point(1,2),Point(1,1),Point(1,1)];
end;