Dynamic variable names: Difference between revisions

m
Line 907:
* The free and readable alternative
* compiles natively to almost any platform, including raspberry PI
*
* This demo uses a dictionary because it is compiled: it cannot make
* dynamic variables at runtime.
*)
USES
Generics.Collections,
SysUtils,
Variants;
 
TYPE
Tdict = specialize TDictionary<string, variant>;
 
VAR
VarName: string;
strValue: string;
VarValue: variant;
D: Tdict;
 
FUNCTION SetType ( strVal: string ): variant;
(* If the value is numeric, store it as numeric, otherwise store it as string *)
BEGIN
Try
SetType := StrToFloat ( strVal ) ;
EXCEPT
SetType := strVal ;
END;
END;
 
BEGIN
D := TDict.Create;
Write ( 'Enter variable name : ' ) ;
ReadLn ( VarName ) ;
Write ( 'Enter variable Value : ' ) ;
ReadLn ( strValue ) ;
VarValue := SetType ( strValue ) ;
TRY
BEGIN
D.Add ( VarName, VarValue ) ;
Write ( VarName ) ;
Write ( ' = ' ) ;
WriteLn ( D [ VarName ] ) ;
END;
FINALLY
D.Free;
END;
END.
</lang>JGAD 2021/05/13
122

edits