Search code examples
delphirecordpascallazarus

Why do I have to use the name of my type to operate it? [Delphi/Lazarus]


type    
  TSpieler = record
    Name  : string;
    Konto,Position : integer;
    Reihe : boolean;
    Panel : TPanel;
  end;   

var
  PL1, PL2, PL3, PL4, PL5 : TSpieler;

function getPlayer;
begin
  Result := PL1;
end;

procedure FeldKaufen;
var
  TestPlayer: TSpieler;
begin
  TestPlayer := getPlayer; {PL2,PL3,PL4,PL5}
  inc(TestPlayer.Konto); {does not save}
  {inc(PL1.Konto);}      {works just fine with every Player}
end;

How can I save PL1 values after giving them to and editing them from TestPlayer?

The problem is I'm getting the name of the player through this getPlayer function, and it is good because it makes the whole code a bit cleaner.


Solution

  • One solution is to use pointers to the Spieler:

    type
      PSpieler = ^TSpieler;
      TSpieler = record
        Name: string;
        Konto, Position: integer;
        Reihe: boolean;
        Panel: TPanel;
      end;
    
    var PL1, PL2, PL3, PL4, PL5: TSpieler;
    
    function getPlayer: PSpieler;
    begin
      Result := @PL1;
    end;
    
    procedure FeldKaufen;
    var TestPlayer: PSpieler;
    begin
      TestPlayer := getPlayer; {PL2,PL3,PL4,PL5}
      inc(TestPlayer.Konto);   {does not save}
      {inc(PL1.Konto);}        {works just fine with every Player}
    end;
    
    procedure TForm1.Button2Click(Sender: TObject);
    begin
      FeldKaufen;
    end;