Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign items in an array all at once in Delphi/Pascal?

Tags:

syntax

delphi

I want to do something like in PHP, Python and most other programming languages:

my_array_name = [128, 38459, 438, 23674...] 

So I tried to replicate this in Delphi/Pascal the best I could:

HSVtoRGB := [0, 0, 0];

(this is for a function which returns an RGB array given HSV values.)

But I am getting errors:

[DCC Error] Unit2.pas(44): E2001 Ordinal type required
[DCC Error] Unit2.pas(45): E2010 Incompatible types: 'HSVRealArray' and 'Set'

Any idea? This is school work - but my teacher didn't know the answer.

like image 697
Thomas O Avatar asked Jun 27 '11 13:06

Thomas O


2 Answers

When it comes to dynamic arrays, yes:

type
  TIntArray = array of integer;

procedure TForm1.Button1Click(Sender: TObject);
var
  MyArr: TIntArray;
begin
  MyArr := TIntArray.Create(10, 20, 30, 40);
end;

When it comes to static arrays, you need to write a helper function:

type
  TIntArray = array[0..2] of integer;

function IntArray(const A, B, C: integer): TIntArray;
begin
  result[0] := A;
  result[1] := B;
  result[2] := C;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  MyArr: TIntArray;
begin
  MyArr := IntArray(10, 20, 30);
end;

This resembles how the Point function creates a TPoint record. (Records and arrays are not the same thing, though.)

like image 73
Andreas Rejbrand Avatar answered Sep 30 '22 12:09

Andreas Rejbrand


This is an area where Delphi turns something that is a simple one-line assignment statement in most languages into something more complicated.

One approach would to declare the value as a typed constant:

type
  HSVRealArray = array[1..3] of real;
const
  constHSVVal: HSVRealArray = (0, 0, 0);
var
  currentValue: HSVRealArray;
begin
  currentValue := constHSVVal;
end;

Another approach is to create utility functions that return the type you need:

function MakeHSVRealArray(H, S, V: Real): HSVRealArray;
begin
  Result[1] := H;
  Result[2] := S;
  Result[3] := V;
end;

currentValue := MakeHSVRealArray(0,0,0);
like image 31
Dan Bartlett Avatar answered Sep 30 '22 13:09

Dan Bartlett