Recent

Author Topic: [solved] how to access variable names by number  (Read 328 times)

Muso

  • Jr. Member
  • **
  • Posts: 93
[solved] how to access variable names by number
« on: April 18, 2021, 07:41:32 pm »
This is propably a noob question but googling around did not help me:

I have to parse a text file with one line. The line contains a comma separated list of values and each value has to be stored into a new variable.

So what I am looking for is a for loop that reads out a value, created a new variable and assign it. So something in this form:

Code: Pascal  [Select][+][-]
  1.   posPrevInt:= 0;
  2.   counterInt:= 1;
  3.   for i:= 1 to 16 do
  4.   begin
  5.    posCurrInt:= Pos(',', ReadString, posPrevInt);
  6.    DummyString:= Copy(ReadLine, posPrevInt, posCurrInt- posPrevInt);
  7.    if not TryStrToFloat(DummyString, Gain1) then
  8.     exit;
  9.    posCommaPrev:= posCommaCurr;
  10.    inc(counterInt);
  11.   end;

Instead of "Gain1" I want to assign the variables Gain1, then Gain2, then Gain3,...

So is there a way to declare the variable name using a number like "Gain+posPrevInt:= " or having the variables in an array to access them?
« Last Edit: April 18, 2021, 09:06:59 pm by Muso »

wp

  • Hero Member
  • *****
  • Posts: 8359
Re: how to access variable names by number
« Reply #1 on: April 18, 2021, 07:51:59 pm »
The easiest way to split a comma-separated list into an array is by using the Split string helper (untested):

Code: Pascal  [Select][+][-]
  1. type
  2.   TFloatArray: array of Double;
  3.  
  4. function GetGains(AString: String; out Gains: TFloatArray): Boolean;
  5. var
  6.   sa: TStringArray;
  7.   i: Integer;
  8. begin
  9.   sa := AString.Split(',');
  10.   SetLength(Gains,Length(sa));
  11.   for i := 0 to High(sa) do
  12.     if not TryStrToFloat(sa[i], Gains[i]) then
  13.     begin
  14.       Gains := nil;
  15.       Result := false;
  16.       exit;
  17.     end;
  18.   Result := true;
  19. end;
Mainly Lazarus trunk / fpc 3.2.0 / all 32-bit on Win-10, but many more...

Muso

  • Jr. Member
  • **
  • Posts: 93
Re: how to access variable names by number
« Reply #2 on: April 18, 2021, 09:06:49 pm »
The easiest way to split a comma-separated list into an array is by using the Split string helper (untested):

Many thanks, works like a charm.

 

TinyPortal © 2005-2018