Dynamic variable names: Difference between revisions

Content added Content deleted
Line 907: Line 907:
* The free and readable alternative
* The free and readable alternative
* compiles natively to almost any platform, including raspberry PI
* compiles natively to almost any platform, including raspberry PI
*
*
* This demo uses a dictionary because it is compiled: it cannot make
* This demo uses a dictionary because it is compiled: it cannot make
* dynamic variables at runtime.
* dynamic variables at runtime.
*)
*)
USES
USES
Generics.Collections,
Generics.Collections,
SysUtils,
SysUtils,
Variants;
Variants;

TYPE
TYPE
Tdict = specialize TDictionary<string, variant>;
Tdict = specialize TDictionary<string, variant>;

VAR
VAR
VarName: string;
VarName: string;
strValue: string;
strValue: string;
VarValue: variant;
VarValue: variant;
D: Tdict;
D: Tdict;


FUNCTION SetType ( strVal: string ): variant;
FUNCTION SetType ( strVal: string ): variant;
(* If the value is numeric, store it as numeric, otherwise store it as string *)
(* If the value is numeric, store it as numeric, otherwise store it as string *)
BEGIN
BEGIN
Try
Try
SetType := StrToFloat ( strVal ) ;
SetType := StrToFloat ( strVal ) ;
EXCEPT
EXCEPT
SetType := strVal ;
SetType := strVal ;
END;
END;
END;
END;


BEGIN
BEGIN
D := TDict.Create;
D := TDict.Create;
Write ( 'Enter variable name : ' ) ;
Write ( 'Enter variable name : ' ) ;
ReadLn ( VarName ) ;
ReadLn ( VarName ) ;
Write ( 'Enter variable Value : ' ) ;
Write ( 'Enter variable Value : ' ) ;
ReadLn ( strValue ) ;
ReadLn ( strValue ) ;
VarValue := SetType ( strValue ) ;
VarValue := SetType ( strValue ) ;
TRY
TRY
BEGIN
BEGIN
D.Add ( VarName, VarValue ) ;
D.Add ( VarName, VarValue ) ;
Write ( VarName ) ;
Write ( VarName ) ;
Write ( ' = ' ) ;
Write ( ' = ' ) ;
WriteLn ( D [ VarName ] ) ;
WriteLn ( D [ VarName ] ) ;
END;
END;
FINALLY
FINALLY
D.Free;
D.Free;
END;
END;
END.
END.
</lang>JGAD 2021/05/13
</lang>JGAD 2021/05/13