Delphi array initialization

后端 未结 3 873
挽巷
挽巷 2021-01-04 01:19

I currently have this, and it sucks:

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

class function rotationTable.offsets(pType, rotState, dir: integer): TpointA         


        
3条回答
  •  无人及你
    2021-01-04 01:48

    Plainth's answer demonstrates the constructor-like syntax for dynamic arrays. You can use that directly on a TPoint array to yield a much simpler helper function:

    type
      TPointDynArray = array of TPoint;
      T4PointArray = array[0..3] of TPoint;
    
    function PointDynArrayTo4PointArray(const input: TPointDynArray): T4PointArray;
    var
      i: Integer;
    begin
      Assert(Length(input) = Length(Result));
      for i := 0 to High(input) do
        Result[i] := input[i];
    end;
    
    class function rotationTable.offsets(pType, rotState, dir: integer): T4PointArray;
    begin
      // New dynamic-array-constructor syntax here
      Result := PointDynArrayTo4PointArray(TPointDynArray.Create(
        Point(1,1), Point(1,2), Point(1,1), Point(1,1)));
    end;
    

    But that's overkill. Delphi also lets you define open arrays inline, and there's no additional constructor call to write. The result uses your original proposed syntax, but with the array wrapped inside a function call. It will work in all Delphi versions, whereas the "Create" syntax above is fairly new.

    function PointOpenArrayTo4PointArray(const input: array of TPoint): T4PointArray;
    var
      i: Integer;
    begin
      Assert(Length(input) = Length(Result));
      for i := 0 to High(input) do
        Result[i] := input[i];
    end;
    
    class function rotationTable.offsets(pType, rotState, dir: integer): T4PointArray;
    begin
      Result := PointOpenArrayTo4PointArray(
        [Point(1,1), Point(1,2), Point(1,1), Point(1,1)]);
    end;
    

    You might want to consider using Gerry's answer just to give your arrays of points meaningful names, which might help when debugging and one of the eight magic numbers in those point definitions is wrong.


    Finally, a note on what Delphi meant when it said "the [1, 2, 3, 4] syntax can only work for Integers." That syntax defines a set, not an array. You can't have a set of record values, but you can have a set of integers. A side effect is that the syntax for a set of integers is the same as the syntax for an open array of integers. I think Delphi uses context to figure out which one you mean, but it can sometimes guess wrong.

提交回复
热议问题