[fpc-pascal] Help with TList example

James Richters james at productionautomation.net
Tue Sep 8 13:10:45 CEST 2020


I'm trying to figure out how TList works.  I found the code example below by doing a search, but I can't compile it,  I get Error: Illegal qualifier on the line  
    MyRec.Value := tmp;
  It's indicating the error is on the V of Value

I tried commenting that line out, then I get the same error on
    MyRec.AByte := Byte(tmp);
At the A of AByte

So I commented that out too and then I get the error on 

   Writeln('Value: ', MyRecList[tmp].Value, ' AByte: ', MyRecList[tmp].AByte); 
At the V on Value after MyRecList[tmp].

I don't know enough about the syntax to figure out what's wrong here.  Does anyone have any ideas?  It seems like there is something fundamentally wrong.

I'm trying to make a temporary list of records.  Kind of like a TStringList, but instead of a list of strings, a list of my own custom records.  Perhaps there is a better way?


program Project1;
{$mode objfpc}{$H+}

uses
  SysUtils, Classes;

type
  PMyRec=^TMyRec;
  TMyRec=record
    Value: Integer;
    AByte: Byte;
  end;

  TMyRecList=class(TList)
  private
    function Get(Index: Integer): PMyRec;
  public
    destructor Destroy; override;
    function Add(Value: PMyRec): Integer;
    property Items[Index: Integer]: PMyRec read Get; default;
  end;

{ TMyRecList }

function TMyRecList.Add(Value: PMyRec): Integer;
begin
  Result := inherited Add(Value);
end;

destructor TMyRecList.Destroy;
var
  i: Integer;
begin
  for i := 0 to Count - 1 do
    FreeMem(Items[i]);
  inherited;
end;

function TMyRecList.Get(Index: Integer): PMyRec;
begin
  Result := PMyRec(inherited Get(Index));
end;

var
  MyRecList: TMyRecList;
  MyRec: pMyRec;
  tmp: Integer;
begin
  MyRecList := TMyRecList.Create;
  for tmp := 0 to 9 do
  begin
    GetMem(MyRec, SizeOf(TMyRec));
    MyRec.Value := tmp;
    MyRec.AByte := Byte(tmp);
    MyRecList.Add(MyRec);
  end;

  for tmp := 0 to MyRecList.Count - 1 do
    Writeln('Value: ', MyRecList[tmp].Value, ' AByte: ', MyRecList[tmp].AByte);
  WriteLn('  Press Enter to free the list');
  ReadLn;
  MyRecList.Free;
end.

James



More information about the fpc-pascal mailing list