Dynamic variable names: Difference between revisions
Added Quackery. |
Added Algol 68 |
||
(18 intermediate revisions by 11 users not shown) | |||
Line 1: | Line 1: | ||
{{task|Programming environment operations}} |
{{task|Programming environment operations}} |
||
{{omit from|6502 Assembly}} |
|||
{{omit from|68000 Assembly}} |
|||
{{omit from|Z80 Assembly}} |
|||
;Task: |
;Task: |
||
Create a variable with a user-defined name. |
Create a variable with a user-defined name. |
||
Line 9: | Line 12: | ||
* [[Eval in environment]] is a similar task. |
* [[Eval in environment]] is a similar task. |
||
<br><br> |
<br><br> |
||
=={{header|ALGOL 68}}== |
|||
{{Trans|FreeBasic}} |
|||
This follows the FreeBASIC sample and simulates dynamic variable names using an array of name and values (both STRINGs).<br/> |
|||
Note, Algol 68G has a non-standard <code>to lower</code> procedure, which could be used in the LCASE operator, i.e.: <code>OP LCASE = ( CHAR c )CHAR: to lower( c );</code>. |
|||
<syntaxhighlight lang="algol68"> |
|||
BEGIN # Simulate dynamic variables using an array, translation of the FreeBASIC sample # |
|||
MODE DYNAMICVARIABLE = STRUCT( STRING name, value ); |
|||
OP LCASE = ( CHAR c )CHAR: IF c >= "A" AND c <= "Z" THEN REPR( ( ABS c - ABS "A" ) + ABS "a" ) ELSE c FI; |
|||
OP LCASE = ( STRING s )STRING: |
|||
BEGIN |
|||
STRING lc := s; |
|||
FOR i FROM LWB lc TO UPB lc DO lc[ i ] := LCASE lc[ i ] OD; |
|||
lc |
|||
END # LCASE # ; |
|||
OP TRIM = ( STRING s )STRING: |
|||
BEGIN |
|||
INT left := LWB s, right := UPB s; |
|||
WHILE IF left > right THEN FALSE ELSE s[ left ] = " " FI DO left +:= 1 OD; |
|||
WHILE IF right < left THEN FALSE ELSE s[ right ] = " " FI DO right -:= 1 OD; |
|||
s[ left : right ] |
|||
END # TRIM # ; |
|||
PROC find variable index = ( []DYNAMICVARIABLE a, STRING v, INT n elements )INT: |
|||
BEGIN |
|||
STRING name = LCASE TRIM v; |
|||
INT index := LWB a - 1; |
|||
INT max index = index + n elements; |
|||
FOR i FROM LWB a TO max index WHILE index < LWB a DO |
|||
IF name OF a[ i ] = name THEN index := i FI |
|||
OD; |
|||
index |
|||
END # find variable index # ; |
|||
INT n; |
|||
WHILE |
|||
print( ( "How many variables do you want to create (max 5) " ) ); |
|||
read( ( n, newline ) ); |
|||
n < 0 OR n > 5 |
|||
DO SKIP OD; |
|||
[ 1 : n ]DYNAMICVARIABLE a; |
|||
print( ( newline, "OK, enter the variable names and their values, below", newline ) ); |
|||
FOR i TO n DO |
|||
WHILE |
|||
print( ( " Variable ", whole( i, 0 ), newline ) ); |
|||
print( ( " Name : " ) ); |
|||
read( ( name OF a[ i ], newline ) ); |
|||
name OF a[ i ] := LCASE TRIM name OF a[ i ]; |
|||
# identifiers should not be case-sensitive in Algol 68 though # |
|||
# in upper stropped sources (such as this one) they have to # |
|||
# be in lower case # |
|||
find variable index( a, name OF a[ i ], i - 1 ) > 0 |
|||
DO |
|||
print( ( " Sorry, you've already created a variable of that name, try again", newline ) ) |
|||
OD; |
|||
print( ( " Value : " ) ); |
|||
read( ( value OF a[ i ], newline ) ); |
|||
value OF a[ i ] := TRIM value OF a[ i ] |
|||
OD; |
|||
print( ( newline, "Press q to quit" ) ); |
|||
WHILE |
|||
STRING v; |
|||
print( ( newline, "Which variable do you want to inspect ? " ) ); |
|||
read( ( v, newline ) ); |
|||
v /= "q" AND v /= "Q" |
|||
DO |
|||
IF INT index = find variable index( a, v, n ); |
|||
index = 0 |
|||
THEN |
|||
print( ( "Sorry there's no variable of that name, try again", newline ) ) |
|||
ELSE |
|||
print( ( "It's value is ", value OF a[ index ], newline ) ) |
|||
FI |
|||
OD |
|||
END |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
How many variables do you want to create (max 5) 3 |
|||
OK, enter the variable names and their values, below |
|||
Variable 1 |
|||
Name : v1 |
|||
Value : 123 |
|||
Variable 2 |
|||
Name : abc |
|||
Value : mnop |
|||
Variable 3 |
|||
Name : l3 |
|||
Value : 21 |
|||
Press q to quit |
|||
Which variable do you want to inspect ? L3 |
|||
It's value is 21 |
|||
Which variable do you want to inspect ? MNOP |
|||
Sorry there's no variable of that name, try again |
|||
Which variable do you want to inspect ? AbC |
|||
It's value is mnop |
|||
Which variable do you want to inspect ? q |
|||
</pre> |
|||
=={{header|APL}}== |
=={{header|APL}}== |
||
<syntaxhighlight lang="apl"> |
|||
<lang APL> |
|||
is←{ t←⍵ ⋄ ⎕this⍎⍺,'←t' } ⍝⍝ the 'Slick Willie' function ;) |
is←{ t←⍵ ⋄ ⎕this⍎⍺,'←t' } ⍝⍝ the 'Slick Willie' function ;) |
||
'test' is ⍳2 3 |
'test' is ⍳2 3 |
||
Line 17: | Line 130: | ||
1 1 1 2 1 3 |
1 1 1 2 1 3 |
||
2 1 2 2 2 3 |
2 1 2 2 2 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">name: strip input "enter a variable name: " |
||
value: strip input "enter a variable value: " |
value: strip input "enter a variable value: " |
||
let name value |
let name value |
||
print ["the value of variable" name "is:" var name]</ |
print ["the value of variable" name "is:" var name]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 35: | Line 148: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">InputBox, Dynamic, Variable Name |
||
%Dynamic% = hello |
%Dynamic% = hello |
||
ListVars |
ListVars |
||
MsgBox % %dynamic% ; says hello</ |
MsgBox % %dynamic% ; says hello</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f DYNAMIC_VARIABLE_NAMES.AWK |
# syntax: GAWK -f DYNAMIC_VARIABLE_NAMES.AWK |
||
# Variables created in GAWK's internal SYMTAB (symbol table) can only be accessed via SYMTAB[name] |
# Variables created in GAWK's internal SYMTAB (symbol table) can only be accessed via SYMTAB[name] |
||
Line 78: | Line 191: | ||
printf("\nsymbol table contains %d names of which %d are arrays\n\n",length(SYMTAB),count) |
printf("\nsymbol table contains %d names of which %d are arrays\n\n",length(SYMTAB),count) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 102: | Line 215: | ||
{{works with|Beta BASIC|3.0}}, |
{{works with|Beta BASIC|3.0}}, |
||
{{works with|SAM BASIC}} |
{{works with|SAM BASIC}} |
||
< |
<syntaxhighlight lang="basic">10 INPUT "Enter a variable name", v$ |
||
20 KEYIN "LET "+v$+"=42"</ |
20 KEYIN "LET "+v$+"=42"</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
setlocal enableDelayedExpansion |
setlocal enableDelayedExpansion |
||
Line 119: | Line 232: | ||
::Display the value using delayed expansion |
::Display the value using delayed expansion |
||
echo %name%=!%name%!</ |
echo %name%=!%name%!</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang="bbcbasic"> INPUT "Enter a variable name: " name$ |
||
INPUT "Enter a numeric value: " numeric$ |
INPUT "Enter a numeric value: " numeric$ |
||
dummy% = EVAL("FNassign("+name$+","+numeric$+")") |
dummy% = EVAL("FNassign("+name$+","+numeric$+")") |
||
Line 128: | Line 241: | ||
END |
END |
||
DEF FNassign(RETURN n, v) : n = v : = 0</ |
DEF FNassign(RETURN n, v) : n = v : = 0</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( put$"Enter a variable name: " |
||
& get$:?name |
& get$:?name |
||
& whl |
& whl |
||
Line 139: | Line 252: | ||
& !numeric:?!name |
& !numeric:?!name |
||
& put$(str$("Variable " !name " now has the value " !!name \n)) |
& put$(str$("Variable " !name " now has the value " !!name \n)) |
||
);</ |
);</syntaxhighlight> |
||
=={{header|C sharp}}== |
=={{header|C sharp|C#}}== |
||
{{works with|C sharp|5}} |
{{works with|C sharp|5}} |
||
Not exactly a variable, but ExpandoObject allows adding properties at runtime. |
Not exactly a variable, but ExpandoObject allows adding properties at runtime. |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Dynamic; |
using System.Dynamic; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 160: | Line 273: | ||
Console.WriteLine(expando.foo); |
Console.WriteLine(expando.foo); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Hello world! |
Hello world! |
||
</pre> |
|||
=={{header|C++}}== |
|||
C++ is a compiled language which means that it loses information about names in code in the compilation process of translation to machine code. This means you can't use any information from your code at runtime without manually storing it somewhere. We therefore simulate dynamic variables using an unordered_map. |
|||
<syntaxhighlight lang="c++"> |
|||
#include <algorithm> |
|||
#include <cstdint> |
|||
#include <iostream> |
|||
#include <string> |
|||
#include <unordered_map> |
|||
int main() { |
|||
std::unordered_map<std::string, int32_t> variables; |
|||
std::string name; |
|||
std::cout << "Enter your variable name: " << std::endl; |
|||
std::cin >> name; |
|||
int32_t value; |
|||
std::cout << "Enter your variable value: " << std::endl; |
|||
std::cin >> value; |
|||
variables[name] = value; |
|||
std::cout << "You have created a variable '" << name << "' with a value of " << value << ":" << std::endl; |
|||
std::for_each(variables.begin(), variables.end(), |
|||
[](std::pair<std::string, int32_t> pair) { |
|||
std::cout << pair.first << " = " << pair.second << std::endl; |
|||
} |
|||
); |
|||
} |
|||
</syntaxhighlight> |
|||
{{ out }} |
|||
<pre> |
|||
Enter your variable name: |
|||
foo |
|||
Enter your variable value: |
|||
42 |
|||
You have created a variable 'foo' with a value of 42: |
|||
foo = 42 |
|||
</pre> |
</pre> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(eval `(def ~(symbol (read)) 42))</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
The short answer is this: |
The short answer is this: |
||
< |
<syntaxhighlight lang="lisp"> |
||
(setq var-name (read)) ; reads a name into var-name |
(setq var-name (read)) ; reads a name into var-name |
||
(set var-name 1) ; assigns the value 1 to a variable named as entered by the user |
(set var-name 1) ; assigns the value 1 to a variable named as entered by the user |
||
</syntaxhighlight> |
|||
</lang> |
|||
Line 188: | Line 342: | ||
Therefore, there are two parts to dynamically creating a variable: we must declare it special, and give it a value. The first part is accomplished by the <code>proclaim</code> function for making declarations at run-time. The second part is simply assigning to the value slot. |
Therefore, there are two parts to dynamically creating a variable: we must declare it special, and give it a value. The first part is accomplished by the <code>proclaim</code> function for making declarations at run-time. The second part is simply assigning to the value slot. |
||
< |
<syntaxhighlight lang="lisp">(defun rc-create-variable (name initial-value) |
||
"Create a global variable whose name is NAME in the current package and which is bound to INITIAL-VALUE." |
"Create a global variable whose name is NAME in the current package and which is bound to INITIAL-VALUE." |
||
(let ((symbol (intern name))) |
(let ((symbol (intern name))) |
||
(proclaim `(special ,symbol)) |
(proclaim `(special ,symbol)) |
||
(setf (symbol-value symbol) initial-value) |
(setf (symbol-value symbol) initial-value) |
||
symbol))</ |
symbol))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">CL-USER> (rc-create-variable "GREETING" "hello") |
||
GREETING |
GREETING |
||
CL-USER> (print greeting) |
CL-USER> (print greeting) |
||
"hello"</ |
"hello"</syntaxhighlight> |
||
Things to note: |
Things to note: |
||
Line 209: | Line 363: | ||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
In Déjà Vu, variable names are idents, which are completely separate from strings, and cannot easily be created from them. The way around that is to invoke the compiler: |
In Déjà Vu, variable names are idents, which are completely separate from strings, and cannot easily be created from them. The way around that is to invoke the compiler: |
||
< |
<syntaxhighlight lang="dejavu">local :var-name !run-blob !compile-string dup concat( ":" !prompt "Enter a variable name: " ) |
||
local var-name 42 |
local var-name 42 |
||
#Assuming the user types THISISWEIRD, otherwise this'll error |
#Assuming the user types THISISWEIRD, otherwise this'll error |
||
!. THISISWEIRD</ |
!. THISISWEIRD</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Enter a variable name: THISISWEIRD |
<pre>Enter a variable name: THISISWEIRD |
||
Line 220: | Line 374: | ||
=={{header|E}}== |
=={{header|E}}== |
||
In E, there are no global variables, and there is no modification of the local (lexical) environment. However, it is possible to construct a program which binds any given variable name. |
In E, there are no global variables, and there is no modification of the local (lexical) environment. However, it is possible to construct a program which binds any given variable name. |
||
< |
<syntaxhighlight lang="e">def makeNounExpr := <elang:evm.makeNounExpr> |
||
def dynVarName(name) { |
def dynVarName(name) { |
||
Line 246: | Line 400: | ||
? dynVarName("c") |
? dynVarName("c") |
||
# value: [1, 2, "BOO!"]</ |
# value: [1, 2, "BOO!"]</syntaxhighlight> |
||
It is also possible to capture the environment object resulting from the evaluation of the constructed program and use it later; this is done by <code>bindX</code> in [[Eval in environment#E]] (except for the program being constant, which is independent). |
It is also possible to capture the environment object resulting from the evaluation of the constructed program and use it later; this is done by <code>bindX</code> in [[Eval in environment#E]] (except for the program being constant, which is independent). |
||
Line 255: | Line 409: | ||
Dynamic variables are not supported by the language. But it is possible to set a dynamic property. |
Dynamic variables are not supported by the language. But it is possible to set a dynamic property. |
||
ELENA |
ELENA 6.x : |
||
< |
<syntaxhighlight lang="elena">import system'dynamic; |
||
import extensions; |
import extensions; |
||
class TestClass |
class TestClass |
||
{ |
{ |
||
object |
object variables; |
||
constructor() |
constructor() |
||
{ |
{ |
||
variables := new DynamicStruct() |
|||
} |
} |
||
function() |
function() |
||
{ |
{ |
||
auto prop := new MessageName(console.write |
auto prop := new MessageName(console.write("Enter the variable name:").readLine()); |
||
(prop.setPropertyMessage())( |
(prop.setPropertyMessage())(variables,42); |
||
console.printLine(prop.toPrintable(),"=",(prop.getPropertyMessage())( |
console.printLine(prop.toPrintable(),"=",(prop.getPropertyMessage())(variables)).readChar() |
||
} |
} |
||
} |
} |
||
public program = new TestClass();</ |
public program = new TestClass();</syntaxhighlight> |
||
The program should be compiled as a vm-client: |
|||
<pre> |
|||
elena-cli sandbox.l -tvm_console |
|||
</pre> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 287: | Line 445: | ||
A variable is a symbol. A name can be read from the user as a string and interned to a symbol. |
A variable is a symbol. A name can be read from the user as a string and interned to a symbol. |
||
< |
<syntaxhighlight lang="lisp">(set (intern (read-string "Enter variable name: ")) 123)</syntaxhighlight> |
||
This example deliberately doesn't use any temporary variables so their names won't clash with what the user might enter. A <code>set</code> like this hits any <code>let</code> dynamic binding or buffer-local setting in the usual way. |
This example deliberately doesn't use any temporary variables so their names won't clash with what the user might enter. A <code>set</code> like this hits any <code>let</code> dynamic binding or buffer-local setting in the usual way. |
||
=={{header|Epoxy}}== |
|||
The debug library allows you to add, get, and delete variables. |
|||
<syntaxhighlight lang="epoxy">--Add user-defined variable to the stack |
|||
const VarName: io.prompt("Input Variable Name: "), |
|||
VarValue: io.prompt("Input Variable Value: ") |
|||
debug.newvar(VarName,VarValue) |
|||
--Outputting the results |
|||
log(debug.getvar(VarName))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Input Variable Name: Test |
|||
Input Variable Value: Hello, world! |
|||
Hello, world! |
|||
</pre> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
This task uses functions from [[Eval_in_environment#Erlang| Runtime evaluation]]. |
This task uses functions from [[Eval_in_environment#Erlang| Runtime evaluation]]. |
||
<syntaxhighlight lang="erlang"> |
|||
<lang Erlang> |
|||
-module( dynamic_variable_names ). |
-module( dynamic_variable_names ). |
||
Line 302: | Line 477: | ||
Form = runtime_evaluation:form_from_string( erlang:atom_to_list(Variable_name) ++ "." ), |
Form = runtime_evaluation:form_from_string( erlang:atom_to_list(Variable_name) ++ "." ), |
||
io:fwrite( "~p has value ~p~n", [Variable_name, runtime_evaluation:evaluate_form(Form, {Variable_name, 42})] ). |
io:fwrite( "~p has value ~p~n", [Variable_name, runtime_evaluation:evaluate_form(Form, {Variable_name, 42})] ). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 312: | Line 487: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
By convention, variable names are usually symbols, but because dynamic variables are implemented via implicit association lists, any object can be used as the key for a value. In this case, we use the string the user enters. |
By convention, variable names are usually symbols, but because dynamic variables are implemented via implicit association lists, any object can be used as the key for a value. In this case, we use the string the user enters. |
||
<lang |
<syntaxhighlight lang="factor">42 readln set</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">s" VARIABLE " pad swap move |
||
." Variable name: " pad 9 + 80 accept |
." Variable name: " pad 9 + 80 accept |
||
pad swap 9 + evaluate</ |
pad swap 9 + evaluate</syntaxhighlight> |
||
Of course, it is easier for the user to simply type VARIABLE ''name'' at the Forth console. |
Of course, it is easier for the user to simply type VARIABLE ''name'' at the Forth console. |
||
Line 323: | Line 498: | ||
FreeBASIC is a statically typed, compiled language and so it is not possible to create new variables, dynamically, at run time. However, you can make it look to the user like you are doing so with code such as the following. Ideally, a 'map' should be used for an exercise such as this but, as there isn't one built into FB, I've used a dynamic array instead which is searched linearly for the variable name. |
FreeBASIC is a statically typed, compiled language and so it is not possible to create new variables, dynamically, at run time. However, you can make it look to the user like you are doing so with code such as the following. Ideally, a 'map' should be used for an exercise such as this but, as there isn't one built into FB, I've used a dynamic array instead which is searched linearly for the variable name. |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Type DynamicVariable |
Type DynamicVariable |
||
Line 380: | Line 555: | ||
End If |
End If |
||
Loop |
Loop |
||
End</ |
End</syntaxhighlight> |
||
Sample input/output : |
Sample input/output : |
||
Line 420: | Line 595: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap"># As is, will not work if val is a String |
||
Assign := function(var, val) |
Assign := function(var, val) |
||
Read(InputTextString(Concatenation(var, " := ", String(val), ";"))); |
Read(InputTextString(Concatenation(var, " := ", String(val), ";"))); |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Genyris}}== |
=={{header|Genyris}}== |
||
The intern function creates a symbol from an arbitrary string. Defvar creates a binding. Weird symbols are quoted with pipe characters. |
The intern function creates a symbol from an arbitrary string. Defvar creates a binding. Weird symbols are quoted with pipe characters. |
||
< |
<syntaxhighlight lang="genyris">defvar (intern 'This is not a pipe.') 42 |
||
define |<weird>| 2009</ |
define |<weird>| 2009</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
Go is in the same boat as other statically typed, compiled languages here in that variables cannot be created dynamically at runtime. However, we can use the built-in map type to associate names input at runtime with values which, in practice, is just as good. |
Go is in the same boat as other statically typed, compiled languages here in that variables cannot be created dynamically at runtime. However, we can use the built-in map type to associate names input at runtime with values which, in practice, is just as good. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 503: | Line 678: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 543: | Line 718: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">def varname = 'foo' |
||
def value = 42 |
def value = 42 |
||
new GroovyShell(this.binding).evaluate("${varname} = ${value}") |
new GroovyShell(this.binding).evaluate("${varname} = ${value}") |
||
assert foo == 42</ |
assert foo == 42</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">data Var a = Var String a deriving Show |
||
main = do |
main = do |
||
putStrLn "please enter you variable name" |
putStrLn "please enter you variable name" |
||
vName <- getLine |
vName <- getLine |
||
let var = Var vName 42 |
let var = Var vName 42 |
||
putStrLn $ "this is your variable: " ++ show var</ |
putStrLn $ "this is your variable: " ++ show var</syntaxhighlight> |
||
{{omit cat|Unicon}} |
{{omit cat|Unicon}} |
||
=={{Header|Insitux}}== |
|||
This first approach creates a function that creates a variable of that name. |
|||
<syntaxhighlight lang="insitux"> |
|||
(let var-name "hello") |
|||
((eval (str "(var " var-name ")")) 123) |
|||
</syntaxhighlight> |
|||
This second approach puts the variable value directly in the evaluated string. |
|||
<syntaxhighlight lang="insitux"> |
|||
(let var-name "hello") |
|||
(eval (str "(var " var-name " 123)")) |
|||
</syntaxhighlight> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
Line 564: | Line 755: | ||
This code was written for J6.02. In J8.04 you will need to replace require'misc' with require'general/misc/prompt' |
This code was written for J6.02. In J8.04 you will need to replace require'misc' with require'general/misc/prompt' |
||
< |
<syntaxhighlight lang="j">require 'misc' |
||
(prompt 'Enter variable name: ')=: 0</ |
(prompt 'Enter variable name: ')=: 0</syntaxhighlight> |
||
For example: < |
For example: <syntaxhighlight lang="j"> require 'misc' |
||
(prompt 'Enter variable name: ')=: 0 |
(prompt 'Enter variable name: ')=: 0 |
||
Enter variable name: FOO |
Enter variable name: FOO |
||
FOO |
FOO |
||
0</ |
0</syntaxhighlight> |
||
Or, if the name is defined in the variable 'userDefined' |
Or, if the name is defined in the variable 'userDefined' |
||
< |
<syntaxhighlight lang="j"> userDefined=: 'BAR' |
||
(userDefined)=: 1 |
(userDefined)=: 1 |
||
BAR |
BAR |
||
1</ |
1</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
Java does not support dynamic naming of variables. Therefore, HashMap has been implemented here. It is similar to an array but allows the searching of values by String keys instead of simply index numbers. |
Java does not support dynamic naming of variables. Therefore, HashMap has been implemented here. It is similar to an array but allows the searching of values by String keys instead of simply index numbers. |
||
< |
<syntaxhighlight lang="java">public static void main(String... args){ |
||
HashMap<String, Integer> vars = new HashMap<String, Integer>(); |
HashMap<String, Integer> vars = new HashMap<String, Integer>(); |
||
//The variable name is stored as the String. The var type of the variable can be |
//The variable name is stored as the String. The var type of the variable can be |
||
Line 594: | Line 785: | ||
System.out.println(vars.get(str)); |
System.out.println(vars.get(str)); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">var varname = 'foo'; // pretend a user input that |
||
var value = 42; |
var value = 42; |
||
eval('var ' + varname + '=' + value);</ |
eval('var ' + varname + '=' + value);</syntaxhighlight> |
||
Alternatively, without using eval: |
Alternatively, without using eval: |
||
< |
<syntaxhighlight lang="javascript">var varname = prompt('Variable name:'); |
||
var value = 42; |
var value = 42; |
||
this[varname] = value;</ |
this[varname] = value;</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
jq does not have variables in the usual sense, but in practice the key/value pairs of JSON objects can be used as variable/value bindings. Using this approach, the given task can be accomplished using the following program: |
jq does not have variables in the usual sense, but in practice the key/value pairs of JSON objects can be used as variable/value bindings. Using this approach, the given task can be accomplished using the following program: |
||
< |
<syntaxhighlight lang="jq">"Enter a variable name:", |
||
(input as $var |
(input as $var |
||
| ("Enter a value:" , |
| ("Enter a value:" , |
||
(input as $value | { ($var) : $value })))</ |
(input as $value | { ($var) : $value })))</syntaxhighlight> |
||
''Transcript'' |
''Transcript'' |
||
Line 626: | Line 817: | ||
Julia has powerful macros: |
Julia has powerful macros: |
||
< |
<syntaxhighlight lang="julia">print("Insert the variable name: ") |
||
variable = Symbol(readline(STDIN)) |
variable = Symbol(readline(STDIN)) |
||
Line 640: | Line 831: | ||
@show variable |
@show variable |
||
println("If I named the variable x:") |
println("If I named the variable x:") |
||
@show x</ |
@show x</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 655: | Line 846: | ||
Kotlin is a statically typed, compiled language and so it is not possible to create new variables, dynamically, at run time. However, you can make it look to the user like you are doing so with code such as the following which uses a map: |
Kotlin is a statically typed, compiled language and so it is not possible to create new variables, dynamically, at run time. However, you can make it look to the user like you are doing so with code such as the following which uses a map: |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="scala">// version 1.1.4 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 695: | Line 886: | ||
else println("It's value is $v") |
else println("It's value is $v") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Sample input/output: |
Sample input/output: |
||
{{out}} |
{{out}} |
||
Line 727: | Line 918: | ||
Which variable do you want to inspect : q |
Which variable do you want to inspect : q |
||
</pre> |
|||
=={{header|Lang}}== |
|||
<syntaxhighlight lang="lang"> |
|||
fn.print(Enter a variable name:\s) |
|||
$varName = fn.input() |
|||
$value = 42 |
|||
fn.exec(\$$varName = \$value) |
|||
fn.println(fn.exec({{{return $}}}$varName)) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Enter a variable name: X |
|||
42 |
|||
</pre> |
</pre> |
||
Line 733: | Line 940: | ||
The example below outputs a random decimal that was assigned to the variable name entered as part of the GET params. |
The example below outputs a random decimal that was assigned to the variable name entered as part of the GET params. |
||
< |
<syntaxhighlight lang="lasso">local(thename = web_request->param('thename')->asString) |
||
if(#thename->size) => {^ |
if(#thename->size) => {^ |
||
var(#thename = math_random) |
var(#thename = math_random) |
||
Line 739: | Line 946: | ||
else |
else |
||
'<a href="?thename=xyz">Please give the variable a name!</a>' |
'<a href="?thename=xyz">Please give the variable a name!</a>' |
||
^}</ |
^}</syntaxhighlight> |
||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang="lingo">-- varName might contain a string that was entered by a user at runtime |
||
-- A new global variable with a user-defined name can be created at runtime like this: |
-- A new global variable with a user-defined name can be created at runtime like this: |
||
Line 748: | Line 955: | ||
-- An new instance variable (object property) with a user-defined name can be created at runtime like this: |
-- An new instance variable (object property) with a user-defined name can be created at runtime like this: |
||
obj[varName] = 23 -- or obj.setProp(varName, 23)</ |
obj[varName] = 23 -- or obj.setProp(varName, 23)</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">? make readword readword |
||
julie |
julie |
||
12 |
12 |
||
? show :julie |
? show :julie |
||
12</ |
12</syntaxhighlight> |
||
=={{header|Logtalk}}== |
=={{header|Logtalk}}== |
||
Logtalk objects can be create or compiled such that new predicates can be added at runtime. A simple example: |
Logtalk objects can be create or compiled such that new predicates can be added at runtime. A simple example: |
||
< |
<syntaxhighlight lang="logtalk"> |
||
| ?- create_object(Id, [], [set_logtalk_flag(dynamic_declarations,allow)], []), |
| ?- create_object(Id, [], [set_logtalk_flag(dynamic_declarations,allow)], []), |
||
write('Variable name: '), read(Name), |
write('Variable name: '), read(Name), |
||
Line 778: | Line 985: | ||
| ?- o1::foo(X). |
| ?- o1::foo(X). |
||
X = 42. |
X = 42. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">_G[io.read()] = 5 --puts 5 in a global variable named by the user</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module DynamicVariable { |
Module DynamicVariable { |
||
input "Variable Name:", a$ |
input "Variable Name:", a$ |
||
Line 801: | Line 1,008: | ||
Keyboard "George"+chr$(13) |
Keyboard "George"+chr$(13) |
||
DynamicVariable |
DynamicVariable |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M4}}== |
=={{header|M4}}== |
||
< |
<syntaxhighlight lang="m4">Enter foo, please. |
||
define(`inp',esyscmd(`echoinp')) |
define(`inp',esyscmd(`echoinp')) |
||
define(`trim',substr(inp,0,decr(len(inp)))) |
define(`trim',substr(inp,0,decr(len(inp)))) |
||
define(trim,42) |
define(trim,42) |
||
foo</ |
foo</syntaxhighlight> |
||
DOS batch file echoinp.bat: |
DOS batch file echoinp.bat: |
||
Line 818: | Line 1,025: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">varname = InputString["Enter a variable name"]; |
||
varvalue = InputString["Enter a value"]; |
varvalue = InputString["Enter a value"]; |
||
ReleaseHold[ Hold[Set["nameholder", "value"]] /. {"nameholder" -> Symbol[varname], "value" -> varvalue}]; |
ReleaseHold[ Hold[Set["nameholder", "value"]] /. {"nameholder" -> Symbol[varname], "value" -> varvalue}]; |
||
Print[varname, " is now set to ", Symbol[varname]]</ |
Print[varname, " is now set to ", Symbol[varname]]</syntaxhighlight> |
||
{{out|Example output}} |
{{out|Example output}} |
||
<pre>-> testvar is now set to 86</pre> |
<pre>-> testvar is now set to 86</pre> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">/* Use :: for indirect assignment */ |
||
block([name: read("name?"), x: read("value?")], name :: x);</ |
block([name: read("name?"), x: read("value?")], name :: x);</syntaxhighlight> |
||
=={{header|min}}== |
=={{header|min}}== |
||
{{works with|min|0.19.3}} |
{{works with|min|0.19.3}} |
||
< |
<syntaxhighlight lang="min">42 "Enter a variable name" ask define</syntaxhighlight> |
||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
This is done in immediate mode so you can see the variable is created, although you will have to reference it through the indirection operator, "@". |
This is done in immediate mode so you can see the variable is created, although you will have to reference it through the indirection operator, "@". |
||
< |
<syntaxhighlight lang="mumps">USER>KILL ;Clean up workspace |
||
USER>WRITE ;show all variables and definitions |
USER>WRITE ;show all variables and definitions |
||
Line 846: | Line 1,053: | ||
A="GIBBERISH" |
A="GIBBERISH" |
||
GIBBERISH=3.14159</ |
GIBBERISH=3.14159</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
< |
<syntaxhighlight lang="nanoquery">print "Enter a variable name: " |
||
name = input() |
name = input() |
||
print name + " = " |
print name + " = " |
||
exec(name + " = 42") |
exec(name + " = 42") |
||
exec("println " + name)</ |
exec("println " + name)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Enter a variable name: test |
<pre>Enter a variable name: test |
||
Line 863: | Line 1,070: | ||
This solution emulates dynamic variables by mapping a string to a pointer to a variable (using a table). |
This solution emulates dynamic variables by mapping a string to a pointer to a variable (using a table). |
||
< |
<syntaxhighlight lang="nim">import tables |
||
var |
var |
||
Line 879: | Line 1,086: | ||
when isMainModule: |
when isMainModule: |
||
main()</ |
main()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Enter a var name: varZ |
<pre>Enter a var name: varZ |
||
Line 885: | Line 1,092: | ||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">varname = input ("Enter variable name: ", "s"); |
||
value = input ("Enter value: ", "s"); |
value = input ("Enter value: ", "s"); |
||
eval([varname,"=",value]);</ |
eval([varname,"=",value]);</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">: createVar(varname) |
||
"tvar: " varname + eval ; |
"tvar: " varname + eval ; |
||
Line 896: | Line 1,103: | ||
12 myvar put |
12 myvar put |
||
myvar at .</ |
myvar at .</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">eval(Str(input(), "=34"))</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
===Free Pascal=== |
===Free Pascal=== |
||
{{works with|Free Pascal|version 3.2.0 }} |
{{works with|Free Pascal|version 3.2.0 }} |
||
<syntaxhighlight lang="pascal"> |
|||
<lang Pascal> |
|||
PROGRAM ExDynVar; |
PROGRAM ExDynVar; |
||
Line 913: | Line 1,120: | ||
{$ENDIF} |
{$ENDIF} |
||
(* |
(*) |
||
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64 |
|||
The free and readable alternative at C/C++ speeds |
|||
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 |
|||
uses |
|||
Generics.Collections, |
Generics.Collections, |
||
SysUtils, |
SysUtils, |
||
Variants; |
Variants; |
||
TYPE |
TYPE |
||
Line 941: | Line 1,148: | ||
D: Tdict; |
D: Tdict; |
||
FUNCTION SetType ( strVal: ansistring ): variant; |
FUNCTION SetType ( strVal: ansistring ) : variant ; |
||
(* If the value is numeric, store it as numeric, otherwise store it as ansistring *) |
|||
(*) |
|||
If the value is numeric, store it as numeric, otherwise store it as ansistring |
|||
(*) |
|||
BEGIN |
BEGIN |
||
TRY |
TRY |
||
SetType := StrToFloat ( strVal ) ; |
SetType := StrToFloat ( strVal ) ; |
||
Line 949: | Line 1,161: | ||
SetType := strVal ; |
SetType := strVal ; |
||
END; |
END; |
||
END; |
END; |
||
BEGIN |
BEGIN |
||
D := TDict.Create; |
D := TDict.Create; |
||
REPEAT |
REPEAT |
||
Line 971: | Line 1,185: | ||
UNTIL ( strValue = '' ) ; |
UNTIL ( strValue = '' ) ; |
||
D.Free; |
D.Free; |
||
END. |
END. |
||
</ |
</syntaxhighlight>JPD 2021/05/13 |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">print "Enter a variable name: "; |
||
$varname = <STDIN>; # type in "foo" on standard input |
$varname = <STDIN>; # type in "foo" on standard input |
||
chomp($varname); |
chomp($varname); |
||
Line 981: | Line 1,196: | ||
# treated as a "symbolic reference", where they |
# treated as a "symbolic reference", where they |
||
# take the string as the name of the variable |
# take the string as the name of the variable |
||
print "$foo\n"; # prints "42"</ |
print "$foo\n"; # prints "42"</syntaxhighlight> |
||
If you are operating in a strict environment, this isn't possible. You need to use 'eval' in this case |
If you are operating in a strict environment, this isn't possible. You need to use 'eval' in this case |
||
< |
<syntaxhighlight lang="perl">use strict; |
||
print "Enter a variable name: "; |
print "Enter a variable name: "; |
||
Line 991: | Line 1,206: | ||
my $varref = eval('\$' . $varname); |
my $varref = eval('\$' . $varname); |
||
$$varref = 42; |
$$varref = 42; |
||
print "$foo\n"; # prints "42"</ |
print "$foo\n"; # prints "42"</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
=== dictionary === |
=== dictionary === |
||
In a sense, this is kinda faking it: |
In a sense, this is kinda faking it: |
||
< |
<syntaxhighlight lang="phix">constant globals = new_dict() |
||
while 1 do |
while 1 do |
||
Line 1,008: | Line 1,223: | ||
setd(name,data,globals) |
setd(name,data,globals) |
||
end if |
end if |
||
end while</ |
end while</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 1,025: | Line 1,240: | ||
=== dynamic classes === |
=== dynamic classes === |
||
{{libheader|Phix/Class}} |
{{libheader|Phix/Class}} |
||
< |
<syntaxhighlight lang="phix">requires("0.8.2") |
||
class dc dynamic |
class dc dynamic |
||
-- public string fred = "555" -- (predefine some fields if you like) |
-- public string fred = "555" -- (predefine some fields if you like) |
||
Line 1,042: | Line 1,257: | ||
d[name] = data |
d[name] = data |
||
end if |
end if |
||
end while</ |
end while</syntaxhighlight> |
||
Same output as above (for the same input)<br> |
Same output as above (for the same input)<br> |
||
Note you would get a fatal crash were that predefined fred not made public, and you entered that, which you could I suppose avoid by testing the result of get_field_flags(d,name) for SF_PRIVATE (and then skipping the prompt and any attempt to store). |
Note you would get a fatal crash were that predefined fred not made public, and you entered that, which you could I suppose avoid by testing the result of get_field_flags(d,name) for SF_PRIVATE (and then skipping the prompt and any attempt to store). |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"><?php |
||
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input |
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input |
||
$$varname = 42; |
$$varname = 42; |
||
echo "$foo\n"; # prints "42" |
echo "$foo\n"; # prints "42" |
||
?></ |
?></syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de userVariable () |
||
(prin "Enter a variable name: ") |
(prin "Enter a variable name: ") |
||
(let Var (line T) # Read transient symbol |
(let Var (line T) # Read transient symbol |
||
(prin "Enter a value: ") |
(prin "Enter a value: ") |
||
(set Var (read)) # Set symbol's value |
(set Var (read)) # Set symbol's value |
||
(println 'Variable Var 'Value (val Var)) ) ) # Print them</ |
(println 'Variable Var 'Value (val Var)) ) ) # Print them</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Enter a variable name: Tom |
<pre>Enter a variable name: Tom |
||
Line 1,067: | Line 1,282: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell">$variableName = Read-Host |
||
New-Variable $variableName 'Foo' |
New-Variable $variableName 'Foo' |
||
Get-Variable $variableName</ |
Get-Variable $variableName</syntaxhighlight> |
||
=={{header|ProDOS}}== |
=={{header|ProDOS}}== |
||
<lang>editvar /newvar /value=a /userinput=1 /title=Enter a variable name: |
<syntaxhighlight lang="text">editvar /newvar /value=a /userinput=1 /title=Enter a variable name: |
||
editvar /newvar /value=b /userinput=1 /title=Enter a variable title: |
editvar /newvar /value=b /userinput=1 /title=Enter a variable title: |
||
editvar /newvar /value=-a- /title=-b-</ |
editvar /newvar /value=-a- /title=-b-</syntaxhighlight> |
||
=={{header|Prolog}}== |
|||
<syntaxhighlight lang="prolog">test :- read(Name), atomics_to_string([Name, "= 50, writeln('", Name, "' = " , Name, ")"], String), term_string(Term, String), Term.</syntaxhighlight> |
|||
Testing: |
|||
<syntaxhighlight lang="prolog">?- test. |
|||
|: "Foo". |
|||
Foo = 50. |
|||
true. |
|||
</syntaxhighlight> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{works with|Python|2.x}} |
{{works with|Python|2.x}} |
||
< |
<syntaxhighlight lang="python">>>> name = raw_input("Enter a variable name: ") |
||
Enter a variable name: X |
Enter a variable name: X |
||
>>> globals()[name] = 42 |
>>> globals()[name] = 42 |
||
>>> X |
>>> X |
||
42</ |
42</syntaxhighlight> |
||
{{works with|Python|3.x}} |
{{works with|Python|3.x}} |
||
< |
<syntaxhighlight lang="python">>>> name = input("Enter a variable name: ") |
||
Enter a variable name: X |
Enter a variable name: X |
||
>>> globals()[name] = 42 |
>>> globals()[name] = 42 |
||
>>> X |
>>> X |
||
42</ |
42</syntaxhighlight> |
||
Note: most of the time when people ask how to do this on newsgroups and other forums, on investigation, it is found that a neater solution is to '''map name to value in a dictionary'''. |
Note: most of the time when people ask how to do this on newsgroups and other forums, on investigation, it is found that a neater solution is to '''map name to value in a dictionary'''. |
||
Line 1,095: | Line 1,319: | ||
Quackery does not have variables, but it does have ''ancillary stacks'' which can be used as variables. |
Quackery does not have variables, but it does have ''ancillary stacks'' which can be used as variables. |
||
< |
<syntaxhighlight lang="quackery"> [ say "The word " |
||
dup echo$ |
dup echo$ |
||
names find names found iff |
names find names found iff |
||
Line 1,111: | Line 1,335: | ||
$ "[ stack ] is " over join quackery |
$ "[ stack ] is " over join quackery |
||
cr cr |
cr cr |
||
exists? cr ] is task ( --> )</ |
exists? cr ] is task ( --> )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,129: | Line 1,353: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r"># Read the name in from a command prompt |
||
varname <- readline("Please name your variable >") |
varname <- readline("Please name your variable >") |
||
# Make sure the name is valid for a variable |
# Make sure the name is valid for a variable |
||
Line 1,138: | Line 1,362: | ||
#Check that the value has been assigned ok |
#Check that the value has been assigned ok |
||
ls(pattern=varname) |
ls(pattern=varname) |
||
get(varname)</ |
get(varname)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
This works on the Racket REPL: |
This works on the Racket REPL: |
||
<syntaxhighlight lang="racket"> |
|||
<lang Racket> |
|||
-> (begin (printf "Enter some name: ") |
-> (begin (printf "Enter some name: ") |
||
(namespace-set-variable-value! (read) 123)) |
(namespace-set-variable-value! (read) 123)) |
||
Line 1,149: | Line 1,373: | ||
-> bleh |
-> bleh |
||
123 |
123 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 1,156: | Line 1,380: | ||
You can [https://docs.raku.org/language/packages#Interpolating_into_names interpolate strings as variable names]: |
You can [https://docs.raku.org/language/packages#Interpolating_into_names interpolate strings as variable names]: |
||
<lang |
<syntaxhighlight lang="raku" line>our $our-var = 'The our var'; |
||
my $my-var = 'The my var'; |
my $my-var = 'The my var'; |
||
Line 1,167: | Line 1,391: | ||
put qq/Var ($name) ends with value 「{$::('name')}」/; |
put qq/Var ($name) ends with value 「{$::('name')}」/; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">REBOL [ |
||
Title: "Dynamic Variable Name" |
Title: "Dynamic Variable Name" |
||
URL: http://rosettacode.org/wiki/Dynamic_variable_names |
URL: http://rosettacode.org/wiki/Dynamic_variable_names |
||
Line 1,183: | Line 1,407: | ||
; accepts the new word and the string ("Hello!") to be assigned. |
; accepts the new word and the string ("Hello!") to be assigned. |
||
set to-word ask "Variable name? " "Hello!"</ |
set to-word ask "Variable name? " "Hello!"</syntaxhighlight> |
||
{{out|Session output}} |
{{out|Session output}} |
||
<pre>Variable name? glister |
<pre>Variable name? glister |
||
Line 1,191: | Line 1,415: | ||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang="retro">:newVariable ("-) s:get var ; |
||
newVariable: foo</ |
newVariable: foo</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 1,199: | Line 1,423: | ||
:::* check for the minimum number of arguments |
:::* check for the minimum number of arguments |
||
:::* check for a legitimate REXX variable name |
:::* check for a legitimate REXX variable name |
||
< |
<syntaxhighlight lang="rexx">/*REXX program demonstrates the use of dynamic variable names & setting a val.*/ |
||
parse arg newVar newValue |
parse arg newVar newValue |
||
say 'Arguments as they were entered via the command line: ' newVar newValue |
say 'Arguments as they were entered via the command line: ' newVar newValue |
||
Line 1,205: | Line 1,429: | ||
call value newVar, newValue |
call value newVar, newValue |
||
say 'The newly assigned value (as per the VALUE bif)------' newVar value(newVar) |
say 'The newly assigned value (as per the VALUE bif)------' newVar value(newVar) |
||
/*stick a fork in it, we're all done. */</ |
/*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' for the input: <tt> abc 456 </tt> |
'''output''' for the input: <tt> abc 456 </tt> |
||
<pre> |
<pre> |
||
Line 1,214: | Line 1,438: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
See "Enter the variable name: " give cName eval(cName+"=10") |
See "Enter the variable name: " give cName eval(cName+"=10") |
||
See "The variable name = " + cName + " and the variable value = " + eval("return "+cName) + nl |
See "The variable name = " + cName + " and the variable value = " + eval("return "+cName) + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output |
Output |
||
< |
<syntaxhighlight lang="ring"> |
||
Enter the variable name: test |
Enter the variable name: test |
||
The variable name = test and the variable value = 10 |
The variable name = test and the variable value = 10 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
In RLaB all the objects are located in a global list $$. To create a variable dynamically, one writes a new entry into the global list. Consider the following example: |
In RLaB all the objects are located in a global list $$. To create a variable dynamically, one writes a new entry into the global list. Consider the following example: |
||
< |
<syntaxhighlight lang="rlab">>> s = "myusername" |
||
myusername |
myusername |
||
>> $$.[s] = 10; |
>> $$.[s] = 10; |
||
>> myusername |
>> myusername |
||
10</ |
10</syntaxhighlight> |
||
=={{header|RPL}}== |
|||
≪ → uservar |
|||
≪ 42 uservar STO |
|||
"Value of " uservar →STR + " = " uservar EVAL →STR + |
|||
≫ ≫ 'GETVAR' STO |
|||
{{in}} |
|||
<pre> |
|||
Xyz GETVAR |
|||
</pre> |
|||
{{out}} |
|||
<pre> |
|||
1: "Value of 'Xyz' = 42" |
|||
</pre> |
|||
The variable still exists after execution, until the user deletes it through the <code>PURGE</code> instruction. |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">p "Enter a variable name" |
||
x = "@" + gets.chomp! |
x = "@" + gets.chomp! |
||
instance_variable_set x, 42 |
instance_variable_set x, 42 |
||
p "The value of #{x} is #{instance_variable_get x}" |
p "The value of #{x} is #{instance_variable_get x}" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out|Example output}} |
{{out|Example output}} |
||
"Enter a variable name" |
"Enter a variable name" |
||
Line 1,244: | Line 1,482: | ||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">=> (define (create-variable name initial-val) |
||
(eval `(define ,name ,initial-val) (interaction-environment))) |
(eval `(define ,name ,initial-val) (interaction-environment))) |
||
Line 1,251: | Line 1,489: | ||
=> hello |
=> hello |
||
50</ |
50</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
It is not possible to create a new lexical variable at run-time, but there are other various ways to do something similar. |
It is not possible to create a new lexical variable at run-time, but there are other various ways to do something similar. |
||
< |
<syntaxhighlight lang="ruby">var name = read("Enter a variable name: ", String); # type in 'foo' |
||
class DynamicVar(name, value) { |
class DynamicVar(name, value) { |
||
Line 1,265: | Line 1,503: | ||
var v = DynamicVar(name, 42); # creates a dynamic variable |
var v = DynamicVar(name, 42); # creates a dynamic variable |
||
say v.foo; # retrieves the value</ |
say v.foo; # retrieves the value</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
Slate symbols are objects that name methods and slots. "Variable definition" is like defining a method which holds the value of a slot, and "variable access" is just method-call to get that value back. |
Slate symbols are objects that name methods and slots. "Variable definition" is like defining a method which holds the value of a slot, and "variable access" is just method-call to get that value back. |
||
< |
<syntaxhighlight lang="slate">define: #name -> (query: 'Enter a variable name: ') intern. "X" |
||
define: name -> 42. |
define: name -> 42. |
||
X print.</ |
X print.</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Line 1,278: | Line 1,516: | ||
Set that variable to 42. |
Set that variable to 42. |
||
Print that variable's name and value. |
Print that variable's name and value. |
||
< |
<syntaxhighlight lang="smalltalk">| varName | |
||
varName := FillInTheBlankMorph |
varName := FillInTheBlankMorph |
||
request: 'Enter a variable name'. |
request: 'Enter a variable name'. |
||
Line 1,286: | Line 1,524: | ||
show: ''value of ', varName, '''; |
show: ''value of ', varName, '''; |
||
show: '' is ''; |
show: '' is ''; |
||
show: ', varName).</ |
show: ', varName).</syntaxhighlight> |
||
the above creates a variable which is visible only inside the evaluated block (which is considered good style). It will not be visible outside. |
the above creates a variable which is visible only inside the evaluated block (which is considered good style). It will not be visible outside. |
||
A bad style alternative which creates a globally visible variable in the Smalltalk namespace (and is therefore visible everywhere) is: |
A bad style alternative which creates a globally visible variable in the Smalltalk namespace (and is therefore visible everywhere) is: |
||
< |
<syntaxhighlight lang="smalltalk">| varName | |
||
varName := Stdin request: 'Enter a global variable name:'. |
varName := Stdin request: 'Enter a global variable name:'. |
||
Smalltalk at:varName asSymbol put:42. |
Smalltalk at:varName asSymbol put:42. |
||
expr := Stdin request:'Enter an expression:'. |
expr := Stdin request:'Enter an expression:'. |
||
(Compiler evaluate:expr) printCR |
(Compiler evaluate:expr) printCR |
||
</syntaxhighlight> |
|||
</lang> |
|||
Be reminded again: this is considered *very very bad style*, and every programmer doing this should be fired. |
Be reminded again: this is considered *very very bad style*, and every programmer doing this should be fired. |
||
{{out}}<pre>Enter a global variable name: abc |
{{out}}<pre>Enter a global variable name: abc |
||
Line 1,303: | Line 1,541: | ||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
Indirect string reference of variables is a basic feature of Snobol, using the $ operator. trim( ) is needed for Snobol4+. |
Indirect string reference of variables is a basic feature of Snobol, using the $ operator. trim( ) is needed for Snobol4+. |
||
< |
<syntaxhighlight lang="snobol4">* # Get var name from user |
||
output = 'Enter variable name:' |
output = 'Enter variable name:' |
||
invar = trim(input) |
invar = trim(input) |
||
Line 1,313: | Line 1,551: | ||
* Display |
* Display |
||
output = invar ' == ' $invar |
output = invar ' == ' $invar |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Enter variable name: |
<pre>Enter variable name: |
||
Line 1,324: | Line 1,562: | ||
Here a scalar variable is created, but one could create a dataset variable, a matrix... Notice the name of the variable is not "s", but the name stored in the global macro "s". |
Here a scalar variable is created, but one could create a dataset variable, a matrix... Notice the name of the variable is not "s", but the name stored in the global macro "s". |
||
< |
<syntaxhighlight lang="stata">display "Name?" _request(s) |
||
scalar $s=10 |
scalar $s=10 |
||
display $s</ |
display $s</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">puts "Enter a variable name:" |
||
gets stdin varname |
gets stdin varname |
||
set $varname 42 |
set $varname 42 |
||
puts "I have set variable $varname to [set $varname]"</ |
puts "I have set variable $varname to [set $varname]"</syntaxhighlight> |
||
Note that it is more normal to use the user's name to index into a Tcl associative array, as the syntax gets easier to work with in that case: |
Note that it is more normal to use the user's name to index into a Tcl associative array, as the syntax gets easier to work with in that case: |
||
< |
<syntaxhighlight lang="tcl">puts -nonewline "Enter an element name: "; flush stdout |
||
gets stdin elemname |
gets stdin elemname |
||
set ary($elemname) [expr int(rand()*100)] |
set ary($elemname) [expr int(rand()*100)] |
||
puts "I have set element $elemname to $ary($elemname)"</ |
puts "I have set element $elemname to $ary($elemname)"</syntaxhighlight> |
||
Another common method for working with dynamic variables is to make an alias to the variable with a fixed name: |
Another common method for working with dynamic variables is to make an alias to the variable with a fixed name: |
||
< |
<syntaxhighlight lang="tcl">puts -nonewline "Enter a variable name: "; flush stdout |
||
gets stdin varname |
gets stdin varname |
||
upvar 0 $varname v; # The ‘0’ for “current scope” |
upvar 0 $varname v; # The ‘0’ for “current scope” |
||
set v [expr int(rand()*100)] |
set v [expr int(rand()*100)] |
||
puts "I have set variable $varname to $v (see for yourself: [set $varname])"</ |
puts "I have set variable $varname to $v (see for yourself: [set $varname])"</syntaxhighlight> |
||
=={{header|TI-89 BASIC}}== |
=={{header|TI-89 BASIC}}== |
||
< |
<syntaxhighlight lang="ti89b">Local varName,value |
||
InputStr "Variable name", varName |
InputStr "Variable name", varName |
||
Prompt value |
Prompt value |
||
value → #varName</ |
value → #varName</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript"> |
||
$$ MODE TUSCRIPT |
$$ MODE TUSCRIPT |
||
ASK "Enter variablename": name="" |
ASK "Enter variablename": name="" |
||
Line 1,359: | Line 1,597: | ||
@name=$value |
@name=$value |
||
PRINT @name |
PRINT @name |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,371: | Line 1,609: | ||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
< |
<syntaxhighlight lang="bash">read name |
||
declare $name=42 |
declare $name=42 |
||
echo "${name}=${!name}"</ |
echo "${name}=${!name}"</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{libheader|Wren-ioutil}} |
|||
Although Wren is dynamically typed, it is not possible to create new variables at run time. We therefore follow the example of some of the statically typed languages here and use a map instead. |
|||
{{libheader|Wren-trait}} |
|||
<lang ecmascript>import "io" for Stdin, Stdout |
|||
Although Wren is dynamically typed, it is not possible to create new variables at run time. However, we can simulate this using a map which is what the Var class in Wren-trait does under the hood. |
|||
<syntaxhighlight lang="wren">import "./ioutil" for Input |
|||
import "./trait" for Var |
|||
var userVars = {} |
|||
System.print("Enter three variables:") |
System.print("Enter three variables:") |
||
for (i in 0..2) { |
for (i in 0..2) { |
||
var name = Input.text("\n name : ") |
|||
var value = Input.text(" value : ") |
|||
Stdout.flush() |
|||
Var[name] = Num.fromString(value) |
|||
System.write(" value: ") |
|||
Stdout.flush() |
|||
var value = Num.fromString(Stdin.readLine()) |
|||
userVars[name] = value |
|||
} |
} |
||
System.print("\nYour variables are:\n") |
System.print("\nYour variables are:\n") |
||
for (kv in |
for (kv in Var.entries) { |
||
System.print(" %(kv.key) = %(kv.value)") |
System.print(" %(kv.key) = %(kv.value)") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,401: | Line 1,637: | ||
Enter three variables: |
Enter three variables: |
||
name : pip |
name : pip |
||
value: 3 |
value : 3 |
||
name : squeak |
name : squeak |
||
value: 4 |
value : 4 |
||
name : wilfred |
name : wilfred |
||
value: 5 |
value : 5 |
||
Your variables are: |
Your variables are: |
||
Line 1,416: | Line 1,652: | ||
wilfred = 5 |
wilfred = 5 |
||
</pre> |
</pre> |
||
=={{header|Z80 Assembly}}== |
|||
This example is admittedly crude but was made to be as simple as possible. To that end, the variable name was made to be only one letter long. A key press is taken from the user, which is used as an offset into an array of 256 null bytes, and then a value is stored at that offset and retrieved from there. Self-modifying code is used to store the user's input as the offset of the <code>IX</code> register. A more practical implementation would store this value into normal RAM first so that it can be more easily retrieved. |
|||
Both the user variable name and the value of that variable are printed. The value is set to 0x42 automatically before printing it. |
|||
<syntaxhighlight lang="z80">org &8000 |
|||
WaitChar equ &BB06 ;Amstrad CPC BIOS call, loops until user presses a key. That key's ASCII value is returned in A. |
|||
PrintChar equ &BB5A ;Amstrad CPC BIOS call, A is treated as an ASCII value and is printed to the screen. |
|||
getInput: |
|||
call WaitChar |
|||
;returns key press in A |
|||
or a ;set flags according to accumulator |
|||
jp m,getInput |
|||
;most keyboards aren't capable of going over ascii 127 |
|||
;but just in case they can prevent it. |
|||
;IX/IY offsets are signed, thus a key press outside of 7-bit ASCII would index out of bounds |
|||
push af |
|||
call PrintChar ;prints the user variable name to the screen. |
|||
pop af |
|||
call NewLine |
|||
ld (LoadFromUserNamedVariable+2),a ;offset byte is at addr+2 |
|||
ld (StoreToUserNamedVariable+2),a |
|||
; This self-modifying code turns both instances of (IX+0) into (IX+varname) |
|||
ld a,&42 ;set the value of the dynamically named variable |
|||
; to &42 |
|||
ld ix,ExtraRam ;storage location of dynamically named variables |
|||
StoreToUserNamedVariable: |
|||
ld (IX+0),a ;store 42 at the named offset |
|||
;"+0" is overwritten with the dynamic user ram name |
|||
xor a |
|||
dec a |
|||
;just to prove that the value is indeed stored where the code |
|||
; is intending to, set A to 255 so that the next section of |
|||
; code will show that the variable is indeed retrieved and |
|||
; is shown to the screen |
|||
LoadFromUserNamedVariable: |
|||
ld a,(IX+0) ;retrieve the value at the stored offset. The "+0" was overwritten with the user-defined offset. |
|||
call ShowHex ;prints to the terminal the value stored at the dynamically named user variable |
|||
ReturnToBasic |
|||
RET |
|||
ShowHex: ;credit to Keith S. of Chibiakumas |
|||
push af |
|||
and %11110000 |
|||
rrca |
|||
rrca |
|||
rrca |
|||
rrca |
|||
call PrintHexChar |
|||
pop af |
|||
and %00001111 |
|||
;call PrintHexChar |
|||
;execution flows into it naturally. |
|||
PrintHexChar: |
|||
or a ;Clear Carry Flag |
|||
daa |
|||
add a,&F0 |
|||
adc a,&40 |
|||
jp PrintChar |
|||
;ret |
|||
NewLine: |
|||
push af |
|||
ld a,13 ;Carriage return |
|||
call PrintChar |
|||
ld a,10 ;Line Feed |
|||
call PrintChar |
|||
pop af |
|||
ret |
|||
org &9000 |
|||
ExtraRam: |
|||
ds 256,0 ;256 bytes of ram, each initialized to zero</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Ready |
|||
run"go.bas |
|||
s |
|||
42 |
|||
Ready |
|||
</pre> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
zkl doesn't support adding vars to an existing class but can create a new class with new vars: |
zkl doesn't support adding vars to an existing class but can create a new class with new vars: |
||
< |
<syntaxhighlight lang="zkl">vname:="foo"; // or vname:=ask("var name = "); |
||
klass:=Compiler.Compiler.compileText("var %s=123".fmt(vname))(); // compile & run the constructor |
klass:=Compiler.Compiler.compileText("var %s=123".fmt(vname))(); // compile & run the constructor |
||
klass.vars.println(); |
klass.vars.println(); |
||
klass.foo.println(); |
klass.foo.println(); |
||
klass.setVar(vname).println(); // setVar(name,val) sets the var</ |
klass.setVar(vname).println(); // setVar(name,val) sets the var</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,432: | Line 1,770: | ||
=={{header|Zsh}}== |
=={{header|Zsh}}== |
||
< |
<syntaxhighlight lang="zsh">read name |
||
typeset $name=42</ |
typeset $name=42</syntaxhighlight> |
||
{{omit from|ACL2}} |
{{omit from|ACL2}} |
Latest revision as of 21:44, 27 March 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- 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.
ALGOL 68
This follows the FreeBASIC sample and simulates dynamic variable names using an array of name and values (both STRINGs).
Note, Algol 68G has a non-standard to lower
procedure, which could be used in the LCASE operator, i.e.: OP LCASE = ( CHAR c )CHAR: to lower( c );
.
BEGIN # Simulate dynamic variables using an array, translation of the FreeBASIC sample #
MODE DYNAMICVARIABLE = STRUCT( STRING name, value );
OP LCASE = ( CHAR c )CHAR: IF c >= "A" AND c <= "Z" THEN REPR( ( ABS c - ABS "A" ) + ABS "a" ) ELSE c FI;
OP LCASE = ( STRING s )STRING:
BEGIN
STRING lc := s;
FOR i FROM LWB lc TO UPB lc DO lc[ i ] := LCASE lc[ i ] OD;
lc
END # LCASE # ;
OP TRIM = ( STRING s )STRING:
BEGIN
INT left := LWB s, right := UPB s;
WHILE IF left > right THEN FALSE ELSE s[ left ] = " " FI DO left +:= 1 OD;
WHILE IF right < left THEN FALSE ELSE s[ right ] = " " FI DO right -:= 1 OD;
s[ left : right ]
END # TRIM # ;
PROC find variable index = ( []DYNAMICVARIABLE a, STRING v, INT n elements )INT:
BEGIN
STRING name = LCASE TRIM v;
INT index := LWB a - 1;
INT max index = index + n elements;
FOR i FROM LWB a TO max index WHILE index < LWB a DO
IF name OF a[ i ] = name THEN index := i FI
OD;
index
END # find variable index # ;
INT n;
WHILE
print( ( "How many variables do you want to create (max 5) " ) );
read( ( n, newline ) );
n < 0 OR n > 5
DO SKIP OD;
[ 1 : n ]DYNAMICVARIABLE a;
print( ( newline, "OK, enter the variable names and their values, below", newline ) );
FOR i TO n DO
WHILE
print( ( " Variable ", whole( i, 0 ), newline ) );
print( ( " Name : " ) );
read( ( name OF a[ i ], newline ) );
name OF a[ i ] := LCASE TRIM name OF a[ i ];
# identifiers should not be case-sensitive in Algol 68 though #
# in upper stropped sources (such as this one) they have to #
# be in lower case #
find variable index( a, name OF a[ i ], i - 1 ) > 0
DO
print( ( " Sorry, you've already created a variable of that name, try again", newline ) )
OD;
print( ( " Value : " ) );
read( ( value OF a[ i ], newline ) );
value OF a[ i ] := TRIM value OF a[ i ]
OD;
print( ( newline, "Press q to quit" ) );
WHILE
STRING v;
print( ( newline, "Which variable do you want to inspect ? " ) );
read( ( v, newline ) );
v /= "q" AND v /= "Q"
DO
IF INT index = find variable index( a, v, n );
index = 0
THEN
print( ( "Sorry there's no variable of that name, try again", newline ) )
ELSE
print( ( "It's value is ", value OF a[ index ], newline ) )
FI
OD
END
- Output:
How many variables do you want to create (max 5) 3 OK, enter the variable names and their values, below Variable 1 Name : v1 Value : 123 Variable 2 Name : abc Value : mnop Variable 3 Name : l3 Value : 21 Press q to quit Which variable do you want to inspect ? L3 It's value is 21 Which variable do you want to inspect ? MNOP Sorry there's no variable of that name, try again Which variable do you want to inspect ? AbC It's value is mnop Which variable do you want to inspect ? q
APL
is←{ t←⍵ ⋄ ⎕this⍎⍺,'←t' } ⍝⍝ the 'Slick Willie' function ;)
'test' is ⍳2 3
test
1 1 1 2 1 3
2 1 2 2 2 3
Arturo
name: strip input "enter a variable name: "
value: strip input "enter a variable value: "
let name value
print ["the value of variable" name "is:" var name]
- Output:
enter a variable name: myvar enter a variable value: 2021 the value of variable myvar is: 2021
AutoHotkey
InputBox, Dynamic, Variable Name
%Dynamic% = hello
ListVars
MsgBox % %dynamic% ; says hello
AWK
# syntax: GAWK -f DYNAMIC_VARIABLE_NAMES.AWK
# Variables created in GAWK's internal SYMTAB (symbol table) can only be accessed via SYMTAB[name]
BEGIN {
PROCINFO["sorted_in"] = "@ind_str_asc"
show_symbol_table()
while (1) {
printf("enter variable name? ")
getline v_name
if (v_name in SYMTAB) {
printf("name already exists with a value of '%s'\n",SYMTAB[v_name])
continue
}
if (v_name ~ /^$/) {
printf("name is null\n")
continue
}
if (v_name !~ /^[A-Za-z][A-Za-z0-9_]*$/) {
printf("name illegally constructed\n")
continue
}
break
}
printf("enter value? ")
getline v_value
SYMTAB[v_name] = v_value
printf("variable '%s' has been created and assigned the value '%s'\n\n",v_name,v_value)
show_symbol_table()
exit(0)
}
function show_symbol_table( count,i) {
for (i in SYMTAB) {
printf("%s ",i)
if (isarray(SYMTAB[i])) { count++ }
}
printf("\nsymbol table contains %d names of which %d are arrays\n\n",length(SYMTAB),count)
}
- Output:
ARGC ARGIND ARGV BINMODE CONVFMT ENVIRON ERRNO FIELDWIDTHS FILENAME FNR FPAT FS IGNORECASE LINT NF NR OFMT OFS ORS PREC PROCINFO RLENGTH ROUNDMODE RS RSTART RT SUBSEP TEXTDOMAIN v_name v_value symbol table contains 30 names of which 3 are arrays enter variable name? FPAT name already exists with a value of '[^[:space:]]+' enter variable name? 0 name illegally constructed enter variable name? name is null enter variable name? animal enter value? zebra variable 'animal' has been created and assigned the value 'zebra' ARGC ARGIND ARGV BINMODE CONVFMT ENVIRON ERRNO FIELDWIDTHS FILENAME FNR FPAT FS IGNORECASE LINT NF NR OFMT OFS ORS PREC PROCINFO RLENGTH ROUNDMODE RS RSTART RT SUBSEP TEXTDOMAIN animal v_name v_value symbol table contains 31 names of which 3 are arrays
BASIC
,
10 INPUT "Enter a variable name", v$
20 KEYIN "LET "+v$+"=42"
Batch File
@echo off
setlocal enableDelayedExpansion
set /p "name=Enter a variable name: "
set /p "value=Enter a value: "
::Create the variable and set its value
set "%name%=%value%"
::Display the value without delayed expansion
call echo %name%=%%%name%%%
::Display the value using delayed expansion
echo %name%=!%name%!
BBC BASIC
INPUT "Enter a variable name: " name$
INPUT "Enter a numeric value: " numeric$
dummy% = EVAL("FNassign("+name$+","+numeric$+")")
PRINT "Variable " name$ " now has the value "; EVAL(name$)
END
DEF FNassign(RETURN n, v) : n = v : = 0
Bracmat
( put$"Enter a variable name: "
& get$:?name
& whl
' ( put$"Enter a numeric value: "
& get$:?numeric:~#
)
& !numeric:?!name
& put$(str$("Variable " !name " now has the value " !!name \n))
);
C#
Not exactly a variable, but ExpandoObject allows adding properties at runtime.
using System;
using System.Dynamic;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string varname = Console.ReadLine();
//Let's pretend the user has entered "foo"
dynamic expando = new ExpandoObject();
var map = expando as IDictionary<string, object>;
map.Add(varname, "Hello world!");
Console.WriteLine(expando.foo);
}
}
- Output:
Hello world!
C++
C++ is a compiled language which means that it loses information about names in code in the compilation process of translation to machine code. This means you can't use any information from your code at runtime without manually storing it somewhere. We therefore simulate dynamic variables using an unordered_map.
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int32_t> variables;
std::string name;
std::cout << "Enter your variable name: " << std::endl;
std::cin >> name;
int32_t value;
std::cout << "Enter your variable value: " << std::endl;
std::cin >> value;
variables[name] = value;
std::cout << "You have created a variable '" << name << "' with a value of " << value << ":" << std::endl;
std::for_each(variables.begin(), variables.end(),
[](std::pair<std::string, int32_t> pair) {
std::cout << pair.first << " = " << pair.second << std::endl;
}
);
}
- Output:
Enter your variable name: foo Enter your variable value: 42 You have created a variable 'foo' with a value of 42: foo = 42
Clojure
(eval `(def ~(symbol (read)) 42))
Common Lisp
The short answer is this:
(setq var-name (read)) ; reads a name into var-name
(set var-name 1) ; assigns the value 1 to a variable named as entered by the user
The academic answer is this:
In Common Lisp, symbol objects name variables; symbols are produced from strings by way of read
(general syntax) or intern
(specificially retrieving or making a symbol).
Symbols are grouped into packages — roughly namespaces — and any time symbols are created at runtime it is usually good to explicitly specify what package they are created in, outside of user/developer tools for working from the REPL (interactive mode) where the current package *package*
is appropriate.
Within the standard, every variable is either lexical or special (dynamic scope). There is no global lexical environment, so in order to "create a variable", we must either create our own mechanism to remember it for lexical binding in a later evaluation, or create a special variable. It is unspecified what happens when a symbol not lexically bound or declared special is used as a variable.
Every symbol has a value slot — a field which, roughly, contains its current value considered as a special variable.
Therefore, there are two parts to dynamically creating a variable: we must declare it special, and give it a value. The first part is accomplished by the proclaim
function for making declarations at run-time. The second part is simply assigning to the value slot.
(defun rc-create-variable (name initial-value)
"Create a global variable whose name is NAME in the current package and which is bound to INITIAL-VALUE."
(let ((symbol (intern name)))
(proclaim `(special ,symbol))
(setf (symbol-value symbol) initial-value)
symbol))
CL-USER> (rc-create-variable "GREETING" "hello")
GREETING
CL-USER> (print greeting)
"hello"
Things to note:
- Once a symbol has been declared special, it cannot be used as a lexical variable. Because of this potentially-surprising behavior, it is conventional to give all symbols naming special variables distinguished names, typically by asterisks as in
*greeting*
, so that lexical variables will not accidentally be given those names.
- Some implementations do, to some extent, support global non-special variables; in these, because of the preceding problem, it is better to simply set the value slot and not proclaim it special. However, this may provoke undefined-variable warnings since the compiler or interpreter has no information with which to know the symbol is intended to be a variable.
- Common Lisp, by default, is case-insensitive; however it accomplishes this by canonicalizing read input to uppercase; there is syntax to denote a lower or mixed-case symbol name,
|Foo|
orF\o\o
.intern
does not go through the input path (reader), so we must provide the name in uppercase to make an "ordinary" variable name.
Déjà Vu
In Déjà Vu, variable names are idents, which are completely separate from strings, and cannot easily be created from them. The way around that is to invoke the compiler:
local :var-name !run-blob !compile-string dup concat( ":" !prompt "Enter a variable name: " )
local var-name 42
#Assuming the user types THISISWEIRD, otherwise this'll error
!. THISISWEIRD
- Output:
Enter a variable name: THISISWEIRD 42
E
In E, there are no global variables, and there is no modification of the local (lexical) environment. However, it is possible to construct a program which binds any given variable name.
def makeNounExpr := <elang:evm.makeNounExpr>
def dynVarName(name) {
def variable := makeNounExpr(null, name, null)
return e`{
def a := 1
def b := 2
def c := 3
{
def $variable := "BOO!"
[a, b, c]
}
}`.eval(safeScope)
}
? dynVarName("foo")
# value: [1, 2, 3]
? dynVarName("b")
# value: [1, "BOO!", 3]
? dynVarName("c")
# value: [1, 2, "BOO!"]
It is also possible to capture the environment object resulting from the evaluation of the constructed program and use it later; this is done by bindX
in Eval in environment#E (except for the program being constant, which is independent).
Delphi
See Pascal.
Elena
Dynamic variables are not supported by the language. But it is possible to set a dynamic property.
ELENA 6.x :
import system'dynamic;
import extensions;
class TestClass
{
object variables;
constructor()
{
variables := new DynamicStruct()
}
function()
{
auto prop := new MessageName(console.write("Enter the variable name:").readLine());
(prop.setPropertyMessage())(variables,42);
console.printLine(prop.toPrintable(),"=",(prop.getPropertyMessage())(variables)).readChar()
}
}
public program = new TestClass();
The program should be compiled as a vm-client:
elena-cli sandbox.l -tvm_console
- Output:
Enter the variable name:a a=42
Emacs Lisp
A variable is a symbol. A name can be read from the user as a string and interned to a symbol.
(set (intern (read-string "Enter variable name: ")) 123)
This example deliberately doesn't use any temporary variables so their names won't clash with what the user might enter. A set
like this hits any let
dynamic binding or buffer-local setting in the usual way.
Epoxy
The debug library allows you to add, get, and delete variables.
--Add user-defined variable to the stack
const VarName: io.prompt("Input Variable Name: "),
VarValue: io.prompt("Input Variable Value: ")
debug.newvar(VarName,VarValue)
--Outputting the results
log(debug.getvar(VarName))
- Output:
Input Variable Name: Test Input Variable Value: Hello, world! Hello, world!
Erlang
This task uses functions from Runtime evaluation.
-module( dynamic_variable_names ).
-export( [task/0] ).
task() ->
{ok,[Variable_name]} = io:fread( "Variable name? ", "~a" ),
Form = runtime_evaluation:form_from_string( erlang:atom_to_list(Variable_name) ++ "." ),
io:fwrite( "~p has value ~p~n", [Variable_name, runtime_evaluation:evaluate_form(Form, {Variable_name, 42})] ).
- Output:
12> dynamic_variable_names:task(). Variable name? Asd 'Asd' has value 42
Factor
By convention, variable names are usually symbols, but because dynamic variables are implemented via implicit association lists, any object can be used as the key for a value. In this case, we use the string the user enters.
42 readln set
Forth
s" VARIABLE " pad swap move
." Variable name: " pad 9 + 80 accept
pad swap 9 + evaluate
Of course, it is easier for the user to simply type VARIABLE name at the Forth console.
FreeBASIC
FreeBASIC is a statically typed, compiled language and so it is not possible to create new variables, dynamically, at run time. However, you can make it look to the user like you are doing so with code such as the following. Ideally, a 'map' should be used for an exercise such as this but, as there isn't one built into FB, I've used a dynamic array instead which is searched linearly for the variable name.
' 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
Sample input/output :
- Output:
How many variables do you want to create (max 5) ? 3 OK, enter the variable names and their values, below Variable 1 Name : a Value : 1 Variable 2 Name : b Value : 2 Variable 3 Name : b Sorry, you've already created a variable of that name, try again Variable 3 Name : c Value : 4 Press q to quit Which variable do you want to inspect ? b It's value is 2 Which variable do you want to inspect ? c It's value is 4 Which variable do you want to inspect ? a It's value is 1 Which variable do you want to inspect ? q
GAP
# As is, will not work if val is a String
Assign := function(var, val)
Read(InputTextString(Concatenation(var, " := ", String(val), ";")));
end;
Genyris
The intern function creates a symbol from an arbitrary string. Defvar creates a binding. Weird symbols are quoted with pipe characters.
defvar (intern 'This is not a pipe.') 42
define |<weird>| 2009
Go
Go is in the same boat as other statically typed, compiled languages here in that variables cannot be created dynamically at runtime. However, we can use the built-in map type to associate names input at runtime with values which, in practice, is just as good.
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
n := 0
for n < 1 || n > 5 {
fmt.Print("How many integer variables do you want to create (max 5) : ")
scanner.Scan()
n, _ = strconv.Atoi(scanner.Text())
check(scanner.Err())
}
vars := make(map[string]int)
fmt.Println("OK, enter the variable names and their values, below")
for i := 1; i <= n; {
fmt.Println("\n Variable", i)
fmt.Print(" Name : ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
if _, ok := vars[name]; ok {
fmt.Println(" Sorry, you've already created a variable of that name, try again")
continue
}
var value int
var err error
for {
fmt.Print(" Value : ")
scanner.Scan()
value, err = strconv.Atoi(scanner.Text())
check(scanner.Err())
if err != nil {
fmt.Println(" Not a valid integer, try again")
} else {
break
}
}
vars[name] = value
i++
}
fmt.Println("\nEnter q to quit")
for {
fmt.Print("\nWhich variable do you want to inspect : ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
if s := strings.ToLower(name); s == "q" {
return
}
v, ok := vars[name]
if !ok {
fmt.Println("Sorry there's no variable of that name, try again")
} else {
fmt.Println("It's value is", v)
}
}
}
- Output:
Sample input/output:
How many integer variables do you want to create (max 5) : 3 OK, enter the variable names and their values, below Variable 1 Name : pip Value : 1 Variable 2 Name : squeak Value : 2 Variable 3 Name : pip Sorry, you've already created a variable of that name, try again Variable 3 Name : wilfred Value : 3 Enter q to quit Which variable do you want to inspect : squeak It's value is 2 Which variable do you want to inspect : auntie Sorry there's no variable of that name, try again Which variable do you want to inspect : wilfred It's value is 3 Which variable do you want to inspect : q
Groovy
Solution:
def varname = 'foo'
def value = 42
new GroovyShell(this.binding).evaluate("${varname} = ${value}")
assert foo == 42
Haskell
data Var a = Var String a deriving Show
main = do
putStrLn "please enter you variable name"
vName <- getLine
let var = Var vName 42
putStrLn $ "this is your variable: " ++ show var
Tasks listed here have been marked as "un-implementable" in Unicon. Solutions may be impossible to do, too complex to be of any valuable instruction in Unicon, or prohibited by the task definition.
But hey; if you think you can prove us wrong, go for it. :-)
Insitux
This first approach creates a function that creates a variable of that name.
(let var-name "hello")
((eval (str "(var " var-name ")")) 123)
This second approach puts the variable value directly in the evaluated string.
(let var-name "hello")
(eval (str "(var " var-name " 123)"))
J
This code was written for J6.02. In J8.04 you will need to replace require'misc' with require'general/misc/prompt'
require 'misc'
(prompt 'Enter variable name: ')=: 0
For example:
require 'misc'
(prompt 'Enter variable name: ')=: 0
Enter variable name: FOO
FOO
0
Or, if the name is defined in the variable 'userDefined'
userDefined=: 'BAR'
(userDefined)=: 1
BAR
1
Java
Java does not support dynamic naming of variables. Therefore, HashMap has been implemented here. It is similar to an array but allows the searching of values by String keys instead of simply index numbers.
public static void main(String... args){
HashMap<String, Integer> vars = new HashMap<String, Integer>();
//The variable name is stored as the String. The var type of the variable can be
//changed by changing the second data type mentiones. However, it must be an object
//or a wrapper class.
vars.put("Variable name", 3); //declaration of variables
vars.put("Next variable name", 5);
Scanner sc = new Scanner(System.in);
String str = sc.next();
vars.put(str, sc.nextInt()); //accpeting name and value from user
System.out.println(vars.get("Variable name")); //printing of values
System.out.println(vars.get(str));
}
JavaScript
var varname = 'foo'; // pretend a user input that
var value = 42;
eval('var ' + varname + '=' + value);
Alternatively, without using eval:
var varname = prompt('Variable name:');
var value = 42;
this[varname] = value;
jq
jq does not have variables in the usual sense, but in practice the key/value pairs of JSON objects can be used as variable/value bindings. Using this approach, the given task can be accomplished using the following program:
"Enter a variable name:",
(input as $var
| ("Enter a value:" ,
(input as $value | { ($var) : $value })))
Transcript
$ jq -nrR -f program.jq Enter a variable name: abracadabra Enter a value: magic { "abracadabra": "magic" }
Julia
Julia has powerful macros:
print("Insert the variable name: ")
variable = Symbol(readline(STDIN))
expression = quote
$variable = 42
println("Inside quote:")
@show $variable
end
eval(expression)
println("Outside quote:")
@show variable
println("If I named the variable x:")
@show x
- Output:
Insert the variable name: x Inside quote: x = 42 Outside quote: variable = :x x = 42
Kotlin
Kotlin is a statically typed, compiled language and so it is not possible to create new variables, dynamically, at run time. However, you can make it look to the user like you are doing so with code such as the following which uses a map:
// version 1.1.4
fun main(args: Array<String>) {
var n: Int
do {
print("How many integer variables do you want to create (max 5) : ")
n = readLine()!!.toInt()
}
while (n < 1 || n > 5)
val map = mutableMapOf<String, Int>()
var name: String
var value: Int
var i = 1
println("OK, enter the variable names and their values, below")
do {
println("\n Variable $i")
print(" Name : ")
name = readLine()!!
if (map.containsKey(name)) {
println(" Sorry, you've already created a variable of that name, try again")
continue
}
print(" Value : ")
value = readLine()!!.toInt()
map.put(name, value)
i++
}
while (i <= n)
println("\nEnter q to quit")
var v: Int?
while (true) {
print("\nWhich variable do you want to inspect : ")
name = readLine()!!
if (name.toLowerCase() == "q") return
v = map[name]
if (v == null) println("Sorry there's no variable of that name, try again")
else println("It's value is $v")
}
}
Sample input/output:
- Output:
How many integer variables do you want to create (max 5) : 3 OK, enter the variable names and their values, below Variable 1 Name : faith Value : 1 Variable 2 Name : hope Value : 2 Variable 3 Name : hope Sorry, you've already created a variable of that name, try again Variable 3 Name : charity Value : 3 Enter q to quit Which variable do you want to inspect : chastity Sorry there's no variable of that name, try again Which variable do you want to inspect : charity It's value is 3 Which variable do you want to inspect : q
Lang
fn.print(Enter a variable name:\s)
$varName = fn.input()
$value = 42
fn.exec(\$$varName = \$value)
fn.println(fn.exec({{{return $}}}$varName))
- Output:
Enter a variable name: X 42
Lasso
Thread vars in Lasso 9 can have dynamic names, but local variables cannot.
The example below outputs a random decimal that was assigned to the variable name entered as part of the GET params.
local(thename = web_request->param('thename')->asString)
if(#thename->size) => {^
var(#thename = math_random)
var(#thename)
else
'<a href="?thename=xyz">Please give the variable a name!</a>'
^}
Lingo
-- varName might contain a string that was entered by a user at runtime
-- A new global variable with a user-defined name can be created at runtime like this:
(the globals)[varName] = 23 -- or (the globals).setProp(varName, 23)
-- An new instance variable (object property) with a user-defined name can be created at runtime like this:
obj[varName] = 23 -- or obj.setProp(varName, 23)
Logo
? make readword readword
julie
12
? show :julie
12
Logtalk
Logtalk objects can be create or compiled such that new predicates can be added at runtime. A simple example:
| ?- create_object(Id, [], [set_logtalk_flag(dynamic_declarations,allow)], []),
write('Variable name: '), read(Name),
write('Variable value: '), read(Value),
Fact =.. [Name, Value],
Id::assertz(Fact).
Variable name: foo.
Variable value: 42.
Id = o1,
Name = foo,
Value = 42,
Fact = foo(42).
?- o1::current_predicate(foo/1).
true.
| ?- o1::foo(X).
X = 42.
Lua
_G[io.read()] = 5 --puts 5 in a global variable named by the user
M2000 Interpreter
Module DynamicVariable {
input "Variable Name:", a$
a$=filter$(a$," ,+-*/^~'\({=<>})|!$&"+chr$(9)+chr$(127))
While a$ ~ "..*" {a$=mid$(a$, 2)}
If len(a$)=0 then Error "No name found"
If chrcode(a$)<65 then Error "Not a Valid name"
Inline a$+"=1000"
Print eval(a$)=1000
\\ use of a$ as pointer to variable
a$.+=100
Print eval(a$)=1100
\\ list of variables
List
}
Keyboard "George"+chr$(13)
DynamicVariable
M4
Enter foo, please.
define(`inp',esyscmd(`echoinp'))
define(`trim',substr(inp,0,decr(len(inp))))
define(trim,42)
foo
DOS batch file echoinp.bat:
@echo off set /p Input= echo %Input%
Mathematica / Wolfram Language
varname = InputString["Enter a variable name"];
varvalue = InputString["Enter a value"];
ReleaseHold[ Hold[Set["nameholder", "value"]] /. {"nameholder" -> Symbol[varname], "value" -> varvalue}];
Print[varname, " is now set to ", Symbol[varname]]
- Example output:
-> testvar is now set to 86
Maxima
/* Use :: for indirect assignment */
block([name: read("name?"), x: read("value?")], name :: x);
min
42 "Enter a variable name" ask define
MUMPS
This is done in immediate mode so you can see the variable is created, although you will have to reference it through the indirection operator, "@".
USER>KILL ;Clean up workspace
USER>WRITE ;show all variables and definitions
USER>READ "Enter a variable name: ",A
Enter a variable name: GIBBERISH
USER>SET @A=3.14159
USER>WRITE
A="GIBBERISH"
GIBBERISH=3.14159
Nanoquery
print "Enter a variable name: "
name = input()
print name + " = "
exec(name + " = 42")
exec("println " + name)
- Output:
Enter a variable name: test test = 42
Nim
Nim is a compiled language, with powerful Templating and Macros, which are compile-time rather than run-time.
This solution emulates dynamic variables by mapping a string to a pointer to a variable (using a table).
import tables
var
theVar: int = 5
varMap = initTable[string, pointer]()
proc ptrToInt(p: pointer): int =
result = cast[ptr int](p)[]
proc main() =
write(stdout, "Enter a var name: ")
let sVar = readLine(stdin)
varMap[$svar] = theVar.addr
echo "Variable ", sVar, " is ", ptrToInt(varMap[$sVar])
when isMainModule:
main()
- Output:
Enter a var name: varZ Variable varZ is 5
Octave
varname = input ("Enter variable name: ", "s");
value = input ("Enter value: ", "s");
eval([varname,"=",value]);
Oforth
: createVar(varname)
"tvar: " varname + eval ;
"myvar" createVar
12 myvar put
myvar at .
PARI/GP
eval(Str(input(), "=34"))
Pascal
Free Pascal
PROGRAM ExDynVar;
{$IFDEF FPC}
{$mode objfpc}{$H+}{$J-}{R+}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
(*)
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
The free and readable alternative at C/C++ speeds
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 =
{$IFDEF FPC}
specialize
{$ENDIF}
TDictionary < ansistring, variant > ;
VAR
VarName: ansistring;
strValue: ansistring;
VarValue: variant;
D: Tdict;
FUNCTION SetType ( strVal: ansistring ) : variant ;
(*)
If the value is numeric, store it as numeric, otherwise store it as ansistring
(*)
BEGIN
TRY
SetType := StrToFloat ( strVal ) ;
EXCEPT
SetType := strVal ;
END;
END;
BEGIN
D := TDict.Create;
REPEAT
Write ( 'Enter variable name : ' ) ;
ReadLn ( VarName ) ;
Write ( 'Enter variable Value : ' ) ;
ReadLn ( strValue ) ;
VarValue := SetType ( strValue ) ;
TRY
BEGIN
D.AddOrSetValue ( VarName, VarValue ) ;
Write ( VarName ) ;
Write ( ' = ' ) ;
WriteLn ( D [ VarName ] ) ;
END;
EXCEPT
WriteLn ( 'Something went wrong.. Try again' ) ;
END;
UNTIL ( strValue = '' ) ;
D.Free;
END.
JPD 2021/05/13
Perl
print "Enter a variable name: ";
$varname = <STDIN>; # type in "foo" on standard input
chomp($varname);
$$varname = 42; # when you try to dereference a string, it will be
# treated as a "symbolic reference", where they
# take the string as the name of the variable
print "$foo\n"; # prints "42"
If you are operating in a strict environment, this isn't possible. You need to use 'eval' in this case
use strict;
print "Enter a variable name: ";
my $foo;
my $varname = <STDIN>; # type in "foo" on standard input
chomp($varname);
my $varref = eval('\$' . $varname);
$$varref = 42;
print "$foo\n"; # prints "42"
Phix
dictionary
In a sense, this is kinda faking it:
constant globals = new_dict()
while 1 do
string name = prompt_string("Enter name or press Enter to quit:")
if length(name)=0 then exit end if
bool bExists = (getd_index(name,globals)!=NULL)
string prompt = iff(not bExists?"No such name, enter a value:"
:sprintf("Already exists, new value[%s]:",{getd(name,globals)}))
string data = prompt_string(prompt)
if length(data) then
setd(name,data,globals)
end if
end while
- Output:
Enter name or press Enter to quit:fred No such name, enter a value:35 Enter name or press Enter to quit:fred Already exists, new value[35]: Enter name or press Enter to quit:james No such name, enter a value:1 Enter name or press Enter to quit:fred Already exists, new value[35]: Enter name or press Enter to quit:james Already exists, new value[1]: Enter name or press Enter to quit:
dynamic classes
requires("0.8.2")
class dc dynamic
-- public string fred = "555" -- (predefine some fields if you like)
end class
dc d = new()
while 1 do
string name = prompt_string("Enter name or press Enter to quit:")
if length(name)=0 then exit end if
bool bExists = (get_field_type(d,name)!=NULL)
-- bool bExists = string(d[name]) -- alt...
string prompt = iff(not bExists?"No such name, enter a value:"
:sprintf("Already exists, new value[%s]:",{d[name]}))
string data = prompt_string(prompt)
if length(data) then
d[name] = data
end if
end while
Same output as above (for the same input)
Note you would get a fatal crash were that predefined fred not made public, and you entered that, which you could I suppose avoid by testing the result of get_field_flags(d,name) for SF_PRIVATE (and then skipping the prompt and any attempt to store).
PHP
<?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?>
PicoLisp
(de userVariable ()
(prin "Enter a variable name: ")
(let Var (line T) # Read transient symbol
(prin "Enter a value: ")
(set Var (read)) # Set symbol's value
(println 'Variable Var 'Value (val Var)) ) ) # Print them
- Output:
Enter a variable name: Tom Enter a value: 42 Variable "Tom" Value 42 -> 42
PowerShell
$variableName = Read-Host
New-Variable $variableName 'Foo'
Get-Variable $variableName
ProDOS
editvar /newvar /value=a /userinput=1 /title=Enter a variable name:
editvar /newvar /value=b /userinput=1 /title=Enter a variable title:
editvar /newvar /value=-a- /title=-b-
Prolog
test :- read(Name), atomics_to_string([Name, "= 50, writeln('", Name, "' = " , Name, ")"], String), term_string(Term, String), Term.
Testing:
?- test.
|: "Foo".
Foo = 50.
true.
Python
>>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
>>> name = input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
Note: most of the time when people ask how to do this on newsgroups and other forums, on investigation, it is found that a neater solution is to map name to value in a dictionary.
Quackery
Quackery does not have variables, but it does have ancillary stacks which can be used as variables.
[ say "The word "
dup echo$
names find names found iff
[ say " exists." ]
else
[ say " does not exist." ] ] is exists? ( $ --> )
[ $ "Please enter a name: " input
cr
dup exists?
cr cr
dup say "Creating " echo$
say "..."
$ "[ stack ] is " over join quackery
cr cr
exists? cr ] is task ( --> )
- Output:
As a dialogue in the Quackery shell.
/O> task ... Please enter a name: my-ancillary-stack The word my-ancillary-stack does not exist. Creating my-ancillary-stack... The word my-ancillary-stack exists.
R
# Read the name in from a command prompt
varname <- readline("Please name your variable >")
# Make sure the name is valid for a variable
varname <- make.names(varname)
message(paste("The variable being assigned is '", varname, "'"))
# Assign the variable (with value 42) into the user workspace (global environment)
assign(varname, 42)
#Check that the value has been assigned ok
ls(pattern=varname)
get(varname)
Racket
This works on the Racket REPL:
-> (begin (printf "Enter some name: ")
(namespace-set-variable-value! (read) 123))
Enter some name: bleh
-> bleh
123
Raku
(formerly Perl 6)
You can interpolate strings as variable names:
our $our-var = 'The our var';
my $my-var = 'The my var';
my $name = prompt 'Variable name: ';
my $value = $::('name'); # use the right sigil, etc
put qq/Var ($name) starts with value 「$value」/;
$::('name') = 137;
put qq/Var ($name) ends with value 「{$::('name')}」/;
REBOL
REBOL [
Title: "Dynamic Variable Name"
URL: http://rosettacode.org/wiki/Dynamic_variable_names
]
; Here, I ask the user for a name, then convert it to a word and
; assign the value "Hello!" to it. To read this phrase, realize that
; REBOL collects terms from right to left, so "Hello!" is stored for
; future use, then the prompt string "Variable name? " is used as the
; argument to ask (prompts user for input). The result of ask is
; converted to a word so it can be an identifier, then the 'set' word
; accepts the new word and the string ("Hello!") to be assigned.
set to-word ask "Variable name? " "Hello!"
- Session output:
Variable name? glister == "Hello!" >> glister == "Hello!"
Retro
:newVariable ("-) s:get var ;
newVariable: foo
REXX
Checks could've been made to:
- check for the minimum number of arguments
- check for a legitimate REXX variable name
/*REXX program demonstrates the use of dynamic variable names & setting a val.*/
parse arg newVar newValue
say 'Arguments as they were entered via the command line: ' newVar newValue
say
call value newVar, newValue
say 'The newly assigned value (as per the VALUE bif)------' newVar value(newVar)
/*stick a fork in it, we're all done. */
output for the input: abc 456
Arguments as they were entered via the command line = abc 45678.1 The newly assigned value (as per the VALUE bif)------ abc 45678.1
Ring
See "Enter the variable name: " give cName eval(cName+"=10")
See "The variable name = " + cName + " and the variable value = " + eval("return "+cName) + nl
Output
Enter the variable name: test
The variable name = test and the variable value = 10
RLaB
In RLaB all the objects are located in a global list $$. To create a variable dynamically, one writes a new entry into the global list. Consider the following example:
>> s = "myusername"
myusername
>> $$.[s] = 10;
>> myusername
10
RPL
≪ → uservar ≪ 42 uservar STO "Value of " uservar →STR + " = " uservar EVAL →STR + ≫ ≫ 'GETVAR' STO
- Input:
Xyz GETVAR
- Output:
1: "Value of 'Xyz' = 42"
The variable still exists after execution, until the user deletes it through the PURGE
instruction.
Ruby
p "Enter a variable name"
x = "@" + gets.chomp!
instance_variable_set x, 42
p "The value of #{x} is #{instance_variable_get x}"
- Example output:
"Enter a variable name" hello "The value of @hello is 42"
Scheme
=> (define (create-variable name initial-val)
(eval `(define ,name ,initial-val) (interaction-environment)))
=> (create-variable (read) 50)
<hello
=> hello
50
Sidef
It is not possible to create a new lexical variable at run-time, but there are other various ways to do something similar.
var name = read("Enter a variable name: ", String); # type in 'foo'
class DynamicVar(name, value) {
method init {
DynamicVar.def_method(name, ->(_) { value })
}
}
var v = DynamicVar(name, 42); # creates a dynamic variable
say v.foo; # retrieves the value
Slate
Slate symbols are objects that name methods and slots. "Variable definition" is like defining a method which holds the value of a slot, and "variable access" is just method-call to get that value back.
define: #name -> (query: 'Enter a variable name: ') intern. "X"
define: name -> 42.
X print.
Smalltalk
Define a block-temporary variable with name specified by user input. Set that variable to 42. Print that variable's name and value.
| varName |
varName := FillInTheBlankMorph
request: 'Enter a variable name'.
Compiler
evaluate:('| ', varName, ' | ', varName, ' := 42.
Transcript
show: ''value of ', varName, ''';
show: '' is '';
show: ', varName).
the above creates a variable which is visible only inside the evaluated block (which is considered good style). It will not be visible outside.
A bad style alternative which creates a globally visible variable in the Smalltalk namespace (and is therefore visible everywhere) is:
| varName |
varName := Stdin request: 'Enter a global variable name:'.
Smalltalk at:varName asSymbol put:42.
expr := Stdin request:'Enter an expression:'.
(Compiler evaluate:expr) printCR
Be reminded again: this is considered *very very bad style*, and every programmer doing this should be fired.
- Output:
Enter a global variable name: abcEnter an expression: abc squared + 5
1769
SNOBOL4
Indirect string reference of variables is a basic feature of Snobol, using the $ operator. trim( ) is needed for Snobol4+.
* # Get var name from user
output = 'Enter variable name:'
invar = trim(input)
* # Get value from user, assign
output = 'Enter value:'
$invar = trim(input)
* Display
output = invar ' == ' $invar
end
- Output:
Enter variable name: pi Enter value: 3.14159 pi == 3.14159
Stata
Here a scalar variable is created, but one could create a dataset variable, a matrix... Notice the name of the variable is not "s", but the name stored in the global macro "s".
display "Name?" _request(s)
scalar $s=10
display $s
Tcl
puts "Enter a variable name:"
gets stdin varname
set $varname 42
puts "I have set variable $varname to [set $varname]"
Note that it is more normal to use the user's name to index into a Tcl associative array, as the syntax gets easier to work with in that case:
puts -nonewline "Enter an element name: "; flush stdout
gets stdin elemname
set ary($elemname) [expr int(rand()*100)]
puts "I have set element $elemname to $ary($elemname)"
Another common method for working with dynamic variables is to make an alias to the variable with a fixed name:
puts -nonewline "Enter a variable name: "; flush stdout
gets stdin varname
upvar 0 $varname v; # The ‘0’ for “current scope”
set v [expr int(rand()*100)]
puts "I have set variable $varname to $v (see for yourself: [set $varname])"
TI-89 BASIC
Local varName,value
InputStr "Variable name", varName
Prompt value
value → #varName
TUSCRIPT
$$ MODE TUSCRIPT
ASK "Enter variablename": name=""
ASK "Enter value": value=""
TRACE +@name
@name=$value
PRINT @name
Output:
Enter variablename >test Enter value >Hello World! TRACING Scratch-Datei -*TUSTEP.EDT 5 00 TRACE +@name test = Hello World! Hello World!
UNIX Shell
read name
declare $name=42
echo "${name}=${!name}"
Wren
Although Wren is dynamically typed, it is not possible to create new variables at run time. However, we can simulate this using a map which is what the Var class in Wren-trait does under the hood.
import "./ioutil" for Input
import "./trait" for Var
System.print("Enter three variables:")
for (i in 0..2) {
var name = Input.text("\n name : ")
var value = Input.text(" value : ")
Var[name] = Num.fromString(value)
}
System.print("\nYour variables are:\n")
for (kv in Var.entries) {
System.print(" %(kv.key) = %(kv.value)")
}
- Output:
Sample session:
Enter three variables: name : pip value : 3 name : squeak value : 4 name : wilfred value : 5 Your variables are: pip = 3 squeak = 4 wilfred = 5
Z80 Assembly
This example is admittedly crude but was made to be as simple as possible. To that end, the variable name was made to be only one letter long. A key press is taken from the user, which is used as an offset into an array of 256 null bytes, and then a value is stored at that offset and retrieved from there. Self-modifying code is used to store the user's input as the offset of the IX
register. A more practical implementation would store this value into normal RAM first so that it can be more easily retrieved.
Both the user variable name and the value of that variable are printed. The value is set to 0x42 automatically before printing it.
org &8000
WaitChar equ &BB06 ;Amstrad CPC BIOS call, loops until user presses a key. That key's ASCII value is returned in A.
PrintChar equ &BB5A ;Amstrad CPC BIOS call, A is treated as an ASCII value and is printed to the screen.
getInput:
call WaitChar
;returns key press in A
or a ;set flags according to accumulator
jp m,getInput
;most keyboards aren't capable of going over ascii 127
;but just in case they can prevent it.
;IX/IY offsets are signed, thus a key press outside of 7-bit ASCII would index out of bounds
push af
call PrintChar ;prints the user variable name to the screen.
pop af
call NewLine
ld (LoadFromUserNamedVariable+2),a ;offset byte is at addr+2
ld (StoreToUserNamedVariable+2),a
; This self-modifying code turns both instances of (IX+0) into (IX+varname)
ld a,&42 ;set the value of the dynamically named variable
; to &42
ld ix,ExtraRam ;storage location of dynamically named variables
StoreToUserNamedVariable:
ld (IX+0),a ;store 42 at the named offset
;"+0" is overwritten with the dynamic user ram name
xor a
dec a
;just to prove that the value is indeed stored where the code
; is intending to, set A to 255 so that the next section of
; code will show that the variable is indeed retrieved and
; is shown to the screen
LoadFromUserNamedVariable:
ld a,(IX+0) ;retrieve the value at the stored offset. The "+0" was overwritten with the user-defined offset.
call ShowHex ;prints to the terminal the value stored at the dynamically named user variable
ReturnToBasic
RET
ShowHex: ;credit to Keith S. of Chibiakumas
push af
and %11110000
rrca
rrca
rrca
rrca
call PrintHexChar
pop af
and %00001111
;call PrintHexChar
;execution flows into it naturally.
PrintHexChar:
or a ;Clear Carry Flag
daa
add a,&F0
adc a,&40
jp PrintChar
;ret
NewLine:
push af
ld a,13 ;Carriage return
call PrintChar
ld a,10 ;Line Feed
call PrintChar
pop af
ret
org &9000
ExtraRam:
ds 256,0 ;256 bytes of ram, each initialized to zero
- Output:
Ready run"go.bas s 42 Ready
zkl
zkl doesn't support adding vars to an existing class but can create a new class with new vars:
vname:="foo"; // or vname:=ask("var name = ");
klass:=Compiler.Compiler.compileText("var %s=123".fmt(vname))(); // compile & run the constructor
klass.vars.println();
klass.foo.println();
klass.setVar(vname).println(); // setVar(name,val) sets the var
- Output:
L(L("foo",123)) 123 123
Zsh
read name
typeset $name=42
- Programming Tasks
- Programming environment operations
- 6502 Assembly/Omit
- 68000 Assembly/Omit
- Z80 Assembly/Omit
- ALGOL 68
- APL
- Arturo
- AutoHotkey
- AWK
- BASIC
- Batch File
- BBC BASIC
- Bracmat
- C sharp
- C++
- Clojure
- Common Lisp
- Déjà Vu
- E
- Delphi
- Elena
- Emacs Lisp
- Epoxy
- Erlang
- Factor
- Forth
- FreeBASIC
- GAP
- Genyris
- Go
- Groovy
- Haskell
- Maintenance/OmitCategoriesCreated
- Insitux
- J
- Java
- JavaScript
- Jq
- Julia
- Kotlin
- Lang
- Lasso
- Lingo
- Logo
- Logtalk
- Lua
- M2000 Interpreter
- M4
- Mathematica
- Wolfram Language
- Maxima
- Min
- MUMPS
- Nanoquery
- Nim
- Octave
- Oforth
- PARI/GP
- Pascal
- Perl
- Phix
- Phix/Class
- PHP
- PicoLisp
- PowerShell
- ProDOS
- Prolog
- Python
- Quackery
- R
- Racket
- Raku
- REBOL
- Retro
- REXX
- Ring
- RLaB
- RPL
- Ruby
- Scheme
- Sidef
- Slate
- Smalltalk
- SNOBOL4
- Stata
- Tcl
- TI-89 BASIC
- TUSCRIPT
- UNIX Shell
- Wren
- Wren-ioutil
- Wren-trait
- Z80 Assembly
- Zkl
- Zsh
- ACL2/Omit
- Ada/Omit
- AmigaE/Omit
- ALGOL 68/Omit
- C/Omit
- C++/Omit
- D/Omit
- Delphi/Omit
- Fortran/Omit
- GUISS/Omit
- Java/Omit
- Lily/Omit
- Locomotive Basic/Omit
- Metafont/Omit
- NetRexx/Omit
- Octave/Omit
- Pascal/Omit
- Processing/Omit
- PureBasic/Omit
- Rust/Omit
- Swift/Omit
- Zkl/Omit
- ZX Spectrum Basic/Omit