Task

Create a variable with a user-defined name.

The variable name should not be written in the program text, but should be taken from the user dynamically.



See also
   Eval in environment is a similar task.


' FB 1.05.0 Win64
 
Type DynamicVariable
  As String name
  As String value
End Type
 
Function FindVariableIndex(a() as DynamicVariable, v as String, nElements As Integer) As Integer
  v = LCase(Trim(v))
  For i As Integer = 1 To nElements
    If a(i).name = v Then Return i
  Next
  Return 0 
End Function
 
Dim As Integer n, index
Dim As String v
Cls
 
Do
 Input "How many variables do you want to create (max 5) "; n
Loop Until n > 0 AndAlso n < 6 
 
Dim a(1 To n) As DynamicVariable
Print
Print "OK, enter the variable names and their values, below"
 
For i As Integer = 1 to n
  Print
  Print "  Variable"; i
  Input "    Name  : ", a(i).name 
  a(i).name = LCase(Trim(a(i).name)) ' variable names are not case sensitive in FB
  If i > 0 Then
     index = FindVariableIndex(a(), a(i).name, i - 1)
     If index > 0 Then
       Print "  Sorry, you've already created a variable of that name, try again"
       i -= 1
       Continue For
     End If 
  End If
  Input "    Value : ", a(i).value
  a(i).value = LCase(Trim(a(i).value))
Next
 
Print
Print "Press q to quit"
Do
  Print
  Input "Which variable do you want to inspect "; v
  If v = "q" OrElse v = "Q" Then Exit Do
  index = FindVariableIndex(a(), v, n)
  If index = 0 Then
    Print "Sorry there's no variable of that name, try again"
  Else
    Print "It's value is "; a(index).value
  End If
Loop
End