[fpc-pascal] Indexing into records using [] property

Ryan Joseph ryan at thealchemistguild.com
Thu Oct 11 04:35:20 CEST 2018


I’d like to know if there is a solution to the problem of indexing into records using [] properties.

In the example below I have an array of records (a dynamic array for the example) and I’d like to use the [] property to index into the values. The problem is because the array holds records I need to return a pointer to the record so I can access the fields. In the end the only problem is I need to dereference the pointer using ^.

Are there any solutions we could propose to this? Some ideas:

1) I looks like we could have a “var” modifier for function results but that concept has only ever existed in function params (like & in C++).

	function GetValue(i: integer): TVec2; var;

2) Maybe a modifier added to GetValue which tells the compiler to call the function (and result) like a pointer when the indexer is used?

====================================

type
	TVec2 = record
		x, y: integer;
	end;
	TVec2Ptr = ^TVec2;
	TVec2Array = array of TVec2;

type
	TVecArray = class
		values: TVec2Array;
		function GetValue(i: integer): TVec2Ptr;
		procedure Resize(newLength: integer);
		property Indexer[i: integer]: TVec2Ptr read GetValue; default;
	end;


function TVecArray.GetValue(i: integer): TVec2Ptr;
begin
	result := @values[i];
end;

procedure TVecArray.Resize(newLength: integer);
begin
	SetLength(values, newLength);
end;

var
	arr: TVecArray;
begin
	arr := TVecArray.Create;
	arr.Resize(1);
	arr[0]^.x := 100;
	arr[0]^.y := 100;
end.

Regards,
	Ryan Joseph



More information about the fpc-pascal mailing list