[fpc-pascal] Generic routines for both dynamic array and other collections

James Richters james.richters at productionautomation.net
Mon Feb 22 01:07:27 CET 2021


I've been using a lot of dynamic arrays of records lately,  Some are even Dynamic Arrays of records that contain other records, for example:
Type
   XYZ_Record = Record
      X,Y,Z : Double
   End;

   Call_Stack_Record = Record
      Location : LongInt;
      Offset   : XYZ_Record;
      Rotation : Double;
   End;

   Call_Stack : Array of Call_Stack_Record;

Then I do things like:
Call_Stack[I].Offset.X := 12.345

Making a helper to handle "All Possible Dynamic Arrays" would have to handle this kind of dynamic array of record structure... 
then the helper would just end up being way more complicated than just using the dynamic array, because you can't know every kind of array that might be defined.
I honestly don't see what you need a helper for dynamic arrays in the first place.  They are pretty straight forward.

I initialize (or reset) the array with 
SetLength(X,0);   

Then add things to it with:
SetLength(X,Length(X)+1);
X[Length(X)] := Data;

Remove things from it with 
SetLength(X,Length(X)-1);

Search through it with 
For I = 0 to Length(X)-1 Do
   Begin
      If X[I] = Test Then
         Do_Something;
   End;

Etc... 

I had some count variables to keep track of how many elements were in the Arrays,  but I got rid of them all because Length() is already there so I didn't see any reason to clutter up my code with another variable to keep track of... Length() ALWAYS reports an accurate count of the array elements... having a separate count variable could go wrong and be off from the actual number of elements.

James

-----Original Message-----
From: fpc-pascal <fpc-pascal-bounces at lists.freepascal.org> On Behalf Of Sven Barth via fpc-pascal
Sent: Sunday, February 21, 2021 5:00 PM
To: FPC-Pascal users discussions <fpc-pascal at lists.freepascal.org>
Cc: Sven Barth <pascaldragon at googlemail.com>; Ryan Joseph <genericptr at gmail.com>
Subject: Re: [fpc-pascal] Generic routines for both dynamic array and other collections

Am 21.02.2021 um 15:59 schrieb Ryan Joseph via fpc-pascal:
>
>> On Feb 20, 2021, at 7:52 PM, Виктор Матузенко via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>>
>> And how do I write generic helper for all possible dynamic arrays?
> By hand sadly. The RTL has added type helpers for many types but I don't think they added these for dynamic arrays. I agree that dynamic arrays should have a "Count" method by default and the RTL should provide "array of T" for all intrinsic types.

You are supposed to use Length(X). There is no need for a "property". 
One doesn't need to objectify each and everything!

Regards,
Sven
_______________________________________________
fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal



More information about the fpc-pascal mailing list