Recent

Author Topic: [SOLVED] Generics.Collections: Argument cannot be assigned to  (Read 2138 times)

Eugene Loza

  • Hero Member
  • *****
  • Posts: 678
    • My games in Pascal
[SOLVED] Generics.Collections: Argument cannot be assigned to
« on: November 03, 2017, 06:43:57 pm »
Hi all!
Again I'm having a stupid question :)
Generics.Collections offers a TList for records with TList.Items to access the values. However, I can't assign fields of the record this way:
Code: Pascal  [Select][+][-]
  1. program Project1;
  2.  
  3. uses SysUtils,Generics.Collections;
  4.  
  5. type TRec = record
  6.   a: integer;
  7. end;
  8. type TRecList = specialize TList<TRec>;
  9.  
  10. var List: TRecList;
  11.     r: TRec;
  12.  
  13. begin
  14.   List := TRecList.Create;
  15.   r.a := 1;
  16.   List.Add(r);
  17.   List.Items[0].a := -1; //<------ project1.lpr(17,16) Error: Argument cannot be assigned to
  18.   FreeAndNil(List);
  19. end.
  20.  
TObjectList works perfectly in such situation.
Moreover List.Items[0].a += -1; works but doesn't change the value. That really makes me only to guess what's going on here :D
Yes, the "items" definition is
property Items[Index: SizeInt]: T read GetItem write SetItem; default;
So, it's relatively clear why it's read-only. The direct access to the items by
  protected
    FItems: array of T; 

is actually protected... Is there anything I can do here except for moving FItems to Public (i.e. editing the Generics.Collections)?

------

or is there a way to raise FItems up to public without modifying external Generics.Collections unit?
« Last Edit: November 03, 2017, 08:48:20 pm by Eugene Loza »
My FOSS games in FreePascal&CastleGameEngine: https://decoherence.itch.io/ (Sources: https://gitlab.com/EugeneLoza)

michalis

  • Full Member
  • ***
  • Posts: 140
    • Castle Game Engine
Re: Generics.Collections: Argument cannot be assigned to
« Reply #1 on: November 03, 2017, 08:40:08 pm »
Castle Game Engine has TStructList (descendant of TList from Generics.Collections) that has methods "List" and "L" to help with this: https://github.com/castle-engine/castle-engine/blob/master/src/base/castleutils_struct_list.inc .

So you can write

Code: [Select]
MyList.List^[I].MyField := 123;

or (only in FPC ObjFpc mode)

Code: [Select]
MyList.L[I].MyField := 123;

See also https://github.com/castle-engine/castle-engine/issues/63 and https://github.com/eugeneloza/decoherence/issues/291 :)

Eugene Loza

  • Hero Member
  • *****
  • Posts: 678
    • My games in Pascal
Re: Generics.Collections: Argument cannot be assigned to
« Reply #2 on: November 03, 2017, 08:48:08 pm »
Thanks a lot, Michalis!
Yes, I've missed the part with TGenericStructList -> TStructList. I've fixed it and it's working perfectly!
My FOSS games in FreePascal&CastleGameEngine: https://decoherence.itch.io/ (Sources: https://gitlab.com/EugeneLoza)

 

TinyPortal © 2005-2018