00 Votes

Delphi/Lazarus: Create multiple Objects using For-Each-Loop

Question by Guest | 2015-04-25 at 16:07

I have something like this (using Lazarus):

Tile0 := THexagone.Create;
Tile1 := THexagone.Create;
Tile2 := THexagone.Create;
Tile3 := THexagone.Create;
Tile4 := THexagone.Create;
Tile5 := THexagone.Create;
Tile6 := THexagone.Create;
Tile7 := THexagone.Create; 

Can I use something like:

for i:=1 to 7 do
  Tile(i) := THexagone.Create; 

I can't find a way to call a variable by its name like this.

ReplyPositiveNegative
2Best Answer2 Votes

Yes you can do something like this.

However, you should use an array instead of single variables. Look at this example:

var
  Tiles: array of THexagone;
  i: integer;
begin
  SetLength(Tiles, 7);

  for i:= 0 to 7 do begin
    Tiles[i] := THexagone.Create;
  end;
end;

Instead of the variables Tile0 to Tile7, we are declaring an array of the object you would like to create. Then, we are setting its length to 7 and you can loop through the array in order to create your Hexagone Object.
2015-04-25 at 20:23

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.