Dynamic variable names: Difference between revisions
Added Algol 68
m (→Free Pascal) |
(Added Algol 68) |
||
(16 intermediate revisions by 10 users not shown) | |||
Line 1:
{{task|Programming environment operations}}
{{omit from|6502 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|Z80 Assembly}}
;Task:
Create a variable with a user-defined name.
Line 9 ⟶ 12:
* [[Eval in environment]] is a similar task.
<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}}==
<syntaxhighlight lang="apl">
is←{ t←⍵ ⋄ ⎕this⍎⍺,'←t' } ⍝⍝ the 'Slick Willie' function ;)
'test' is ⍳2 3
Line 17 ⟶ 130:
1 1 1 2 1 3
2 1 2 2 2 3
</syntaxhighlight>
=={{header|Arturo}}==
<
value: strip input "enter a variable value: "
let name value
print ["the value of variable" name "is:" var name]</
{{out}}
Line 35 ⟶ 148:
=={{header|AutoHotkey}}==
<
%Dynamic% = hello
ListVars
MsgBox % %dynamic% ; says hello</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f DYNAMIC_VARIABLE_NAMES.AWK
# Variables created in GAWK's internal SYMTAB (symbol table) can only be accessed via SYMTAB[name]
Line 78 ⟶ 191:
printf("\nsymbol table contains %d names of which %d are arrays\n\n",length(SYMTAB),count)
}
</syntaxhighlight>
{{out}}
<pre>
Line 102 ⟶ 215:
{{works with|Beta BASIC|3.0}},
{{works with|SAM BASIC}}
<
20 KEYIN "LET "+v$+"=42"</
=={{header|Batch File}}==
<
setlocal enableDelayedExpansion
Line 119 ⟶ 232:
::Display the value using delayed expansion
echo %name%=!%name%!</
=={{header|BBC BASIC}}==
<
INPUT "Enter a numeric value: " numeric$
dummy% = EVAL("FNassign("+name$+","+numeric$+")")
Line 128 ⟶ 241:
END
DEF FNassign(RETURN n, v) : n = v : = 0</
=={{header|Bracmat}}==
<
& get$:?name
& whl
Line 139 ⟶ 252:
& !numeric:?!name
& put$(str$("Variable " !name " now has the value " !!name \n))
);</
=={{header|C sharp|C#}}==
{{works with|C sharp|5}}
Not exactly a variable, but ExpandoObject allows adding properties at runtime.
<
using System.Dynamic;
using System.Collections.Generic;
Line 160 ⟶ 273:
Console.WriteLine(expando.foo);
}
}</
{{out}}
<pre>
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>
=={{header|Clojure}}==
<
=={{header|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
</syntaxhighlight>
Line 188 ⟶ 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.
<
"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))</
<
GREETING
CL-USER> (print greeting)
"hello"</
Things to note:
Line 209 ⟶ 363:
=={{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:
<
local var-name 42
#Assuming the user types THISISWEIRD, otherwise this'll error
!. THISISWEIRD</
{{out}}
<pre>Enter a variable name: THISISWEIRD
Line 220 ⟶ 374:
=={{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.
<
def dynVarName(name) {
Line 246 ⟶ 400:
? 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 <code>bindX</code> in [[Eval in environment#E]] (except for the program being constant, which is independent).
Line 255 ⟶ 409:
Dynamic variables are not supported by the language. But it is possible to set a dynamic property.
ELENA
<
import extensions;
class TestClass
{
object
constructor()
{
}
function()
{
auto prop := new MessageName(console.write
(prop.setPropertyMessage())(
console.printLine(prop.toPrintable(),"=",(prop.getPropertyMessage())(
}
}
public program = new TestClass();</
The program should be compiled as a vm-client:
<pre>
elena-cli sandbox.l -tvm_console
</pre>
{{out}}
<pre>
Line 287 ⟶ 445:
A variable is a symbol. A name can be read from the user as a string and interned to a symbol.
<
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}}==
This task uses functions from [[Eval_in_environment#Erlang| Runtime evaluation]].
<syntaxhighlight lang="erlang">
-module( dynamic_variable_names ).
Line 302 ⟶ 477:
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})] ).
</syntaxhighlight>
{{out}}
<pre>
Line 312 ⟶ 487:
=={{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.
<syntaxhighlight lang
=={{header|Forth}}==
<
." 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.
Line 323 ⟶ 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.
<
Type DynamicVariable
Line 380 ⟶ 555:
End If
Loop
End</
Sample input/output :
Line 420 ⟶ 595:
=={{header|GAP}}==
<
Assign := function(var, val)
Read(InputTextString(Concatenation(var, " := ", String(val), ";")));
end;</
=={{header|Genyris}}==
The intern function creates a symbol from an arbitrary string. Defvar creates a binding. Weird symbols are quoted with pipe characters.
<
define |<weird>| 2009</
=={{header|Go}}==
{{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.
<
import (
Line 503 ⟶ 678:
}
}
}</
{{out}}
Line 543 ⟶ 718:
=={{header|Groovy}}==
Solution:
<
def value = 42
new GroovyShell(this.binding).evaluate("${varname} = ${value}")
assert foo == 42</
=={{header|Haskell}}==
<
main = do
putStrLn "please enter you variable name"
vName <- getLine
let var = Var vName 42
putStrLn $ "this is your variable: " ++ show var</
{{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}}==
Line 564 ⟶ 755:
This code was written for J6.02. In J8.04 you will need to replace require'misc' with require'general/misc/prompt'
<
(prompt 'Enter variable name: ')=: 0</
For example: <
(prompt 'Enter variable name: ')=: 0
Enter variable name: FOO
FOO
0</
Or, if the name is defined in the variable 'userDefined'
<
(userDefined)=: 1
BAR
1</
=={{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.
<
HashMap<String, Integer> vars = new HashMap<String, Integer>();
//The variable name is stored as the String. The var type of the variable can be
Line 594 ⟶ 785:
System.out.println(vars.get(str));
}
</syntaxhighlight>
=={{header|JavaScript}}==
<
var value = 42;
eval('var ' + varname + '=' + value);</
Alternatively, without using eval:
<
var value = 42;
this[varname] = value;</
=={{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:
<
(input as $var
| ("Enter a value:" ,
(input as $value | { ($var) : $value })))</
''Transcript''
Line 626 ⟶ 817:
Julia has powerful macros:
<
variable = Symbol(readline(STDIN))
Line 640 ⟶ 831:
@show variable
println("If I named the variable x:")
@show x</
{{out}}
Line 655 ⟶ 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:
{{trans|FreeBASIC}}
<
fun main(args: Array<String>) {
Line 695 ⟶ 886:
else println("It's value is $v")
}
}</
Sample input/output:
{{out}}
Line 727 ⟶ 918:
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>
Line 733 ⟶ 940:
The example below outputs a random decimal that was assigned to the variable name entered as part of the GET params.
<
if(#thename->size) => {^
var(#thename = math_random)
Line 739 ⟶ 946:
else
'<a href="?thename=xyz">Please give the variable a name!</a>'
^}</
=={{header|Lingo}}==
<
-- A new global variable with a user-defined name can be created at runtime like this:
Line 748 ⟶ 955:
-- 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)</
=={{header|Logo}}==
<
julie
12
? show :julie
12</
=={{header|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),
Line 778 ⟶ 985:
| ?- o1::foo(X).
X = 42.
</syntaxhighlight>
=={{header|Lua}}==
<
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module DynamicVariable {
input "Variable Name:", a$
Line 801 ⟶ 1,008:
Keyboard "George"+chr$(13)
DynamicVariable
</syntaxhighlight>
=={{header|M4}}==
<
define(`inp',esyscmd(`echoinp'))
define(`trim',substr(inp,0,decr(len(inp))))
define(trim,42)
foo</
DOS batch file echoinp.bat:
Line 818 ⟶ 1,025:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
varvalue = InputString["Enter a value"];
ReleaseHold[ Hold[Set["nameholder", "value"]] /. {"nameholder" -> Symbol[varname], "value" -> varvalue}];
Print[varname, " is now set to ", Symbol[varname]]</
{{out|Example output}}
<pre>-> testvar is now set to 86</pre>
=={{header|Maxima}}==
<
block([name: read("name?"), x: read("value?")], name :: x);</
=={{header|min}}==
{{works with|min|0.19.3}}
<
=={{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, "@".
<
USER>WRITE ;show all variables and definitions
Line 846 ⟶ 1,053:
A="GIBBERISH"
GIBBERISH=3.14159</
=={{header|Nanoquery}}==
<
name = input()
print name + " = "
exec(name + " = 42")
exec("println " + name)</
{{out}}
<pre>Enter a variable name: test
Line 863 ⟶ 1,070:
This solution emulates dynamic variables by mapping a string to a pointer to a variable (using a table).
<
var
Line 879 ⟶ 1,086:
when isMainModule:
main()</
{{out}}
<pre>Enter a var name: varZ
Line 885 ⟶ 1,092:
=={{header|Octave}}==
<
value = input ("Enter value: ", "s");
eval([varname,"=",value]);</
=={{header|Oforth}}==
<
"tvar: " varname + eval ;
Line 896 ⟶ 1,103:
12 myvar put
myvar at .</
=={{header|PARI/GP}}==
<
=={{header|Pascal}}==
===Free Pascal===
{{works with|Free Pascal|version 3.2.0 }}
<syntaxhighlight lang="pascal">
PROGRAM ExDynVar;
Line 980 ⟶ 1,187:
END.
</
=={{header|Perl}}==
<
$varname = <STDIN>; # type in "foo" on standard input
chomp($varname);
Line 989 ⟶ 1,196:
# 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
<
print "Enter a variable name: ";
Line 999 ⟶ 1,206:
my $varref = eval('\$' . $varname);
$$varref = 42;
print "$foo\n"; # prints "42"</
=={{header|Phix}}==
=== dictionary ===
In a sense, this is kinda faking it:
<
while 1 do
Line 1,016 ⟶ 1,223:
setd(name,data,globals)
end if
end while</
{{Out}}
<pre>
Line 1,033 ⟶ 1,240:
=== dynamic classes ===
{{libheader|Phix/Class}}
<
class dc dynamic
-- public string fred = "555" -- (predefine some fields if you like)
Line 1,050 ⟶ 1,257:
d[name] = data
end if
end while</
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).
=={{header|PHP}}==
<
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?></
=={{header|PicoLisp}}==
<
(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</
{{out}}
<pre>Enter a variable name: Tom
Line 1,075 ⟶ 1,282:
=={{header|PowerShell}}==
<
New-Variable $variableName 'Foo'
Get-Variable $variableName</
=={{header|ProDOS}}==
<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=-a- /title=-b-</
=={{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}}==
{{works with|Python|2.x}}
<
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42</
{{works with|Python|3.x}}
<
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'''.
Line 1,103 ⟶ 1,319:
Quackery does not have variables, but it does have ''ancillary stacks'' which can be used as variables.
<
dup echo$
names find names found iff
Line 1,119 ⟶ 1,335:
$ "[ stack ] is " over join quackery
cr cr
exists? cr ] is task ( --> )</
{{out}}
Line 1,137 ⟶ 1,353:
=={{header|R}}==
<
varname <- readline("Please name your variable >")
# Make sure the name is valid for a variable
Line 1,146 ⟶ 1,362:
#Check that the value has been assigned ok
ls(pattern=varname)
get(varname)</
=={{header|Racket}}==
This works on the Racket REPL:
<syntaxhighlight lang="racket">
-> (begin (printf "Enter some name: ")
(namespace-set-variable-value! (read) 123))
Line 1,157 ⟶ 1,373:
-> bleh
123
</syntaxhighlight>
=={{header|Raku}}==
Line 1,164 ⟶ 1,380:
You can [https://docs.raku.org/language/packages#Interpolating_into_names interpolate strings as variable names]:
<syntaxhighlight lang="raku"
my $my-var = 'The my var';
Line 1,175 ⟶ 1,391:
put qq/Var ($name) ends with value 「{$::('name')}」/;
</syntaxhighlight>
=={{header|REBOL}}==
<
Title: "Dynamic Variable Name"
URL: http://rosettacode.org/wiki/Dynamic_variable_names
Line 1,191 ⟶ 1,407:
; accepts the new word and the string ("Hello!") to be assigned.
set to-word ask "Variable name? " "Hello!"</
{{out|Session output}}
<pre>Variable name? glister
Line 1,199 ⟶ 1,415:
=={{header|Retro}}==
<
newVariable: foo</
=={{header|REXX}}==
Line 1,207 ⟶ 1,423:
:::* check for the minimum number of arguments
:::* check for a legitimate REXX variable name
<
parse arg newVar newValue
say 'Arguments as they were entered via the command line: ' newVar newValue
Line 1,213 ⟶ 1,429:
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: <tt> abc 456 </tt>
<pre>
Line 1,222 ⟶ 1,438:
=={{header|Ring}}==
<
See "Enter the variable name: " give cName eval(cName+"=10")
See "The variable name = " + cName + " and the variable value = " + eval("return "+cName) + nl
</syntaxhighlight>
Output
<
Enter the variable name: test
The variable name = test and the variable value = 10
</syntaxhighlight>
=={{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:
<
myusername
>> $$.[s] = 10;
>> myusername
10</
=={{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}}==
<
x = "@" + gets.chomp!
instance_variable_set x, 42
p "The value of #{x} is #{instance_variable_get x}"
</syntaxhighlight>
{{out|Example output}}
"Enter a variable name"
Line 1,252 ⟶ 1,482:
=={{header|Scheme}}==
<
(eval `(define ,name ,initial-val) (interaction-environment)))
Line 1,259 ⟶ 1,489:
=> hello
50</
=={{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.
<
class DynamicVar(name, value) {
Line 1,273 ⟶ 1,503:
var v = DynamicVar(name, 42); # creates a dynamic variable
say v.foo; # retrieves the value</
=={{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.
<
define: name -> 42.
X print.</
=={{header|Smalltalk}}==
Line 1,286 ⟶ 1,516:
Set that variable to 42.
Print that variable's name and value.
<
varName := FillInTheBlankMorph
request: 'Enter a variable name'.
Line 1,294 ⟶ 1,524:
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 := Stdin request: 'Enter a global variable name:'.
Smalltalk at:varName asSymbol put:42.
expr := Stdin request:'Enter an expression:'.
(Compiler evaluate:expr) printCR
</syntaxhighlight>
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
Line 1,311 ⟶ 1,541:
=={{header|SNOBOL4}}==
Indirect string reference of variables is a basic feature of Snobol, using the $ operator. trim( ) is needed for Snobol4+.
<
output = 'Enter variable name:'
invar = trim(input)
Line 1,321 ⟶ 1,551:
* Display
output = invar ' == ' $invar
end</
{{out}}
<pre>Enter variable name:
Line 1,332 ⟶ 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".
<
scalar $s=10
display $s</
=={{header|Tcl}}==
<
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:
<
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:
<
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])"</
=={{header|TI-89 BASIC}}==
<
InputStr "Variable name", varName
Prompt value
value → #varName</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
ASK "Enter variablename": name=""
Line 1,367 ⟶ 1,597:
@name=$value
PRINT @name
</syntaxhighlight>
Output:
<pre>
Line 1,379 ⟶ 1,609:
=={{header|UNIX Shell}}==
<
declare $name=42
echo "${name}=${!name}"</
=={{header|Wren}}==
{{libheader|Wren-ioutil}}
{{libheader|Wren-trait}}
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
System.print("Enter three variables:")
for (i in 0..2) {
var value = Input.text(" value : ")
}
System.print("\nYour variables are:\n")
for (kv in
System.print(" %(kv.key) = %(kv.value)")
}</
{{out}}
Line 1,409 ⟶ 1,637:
Enter three variables:
name : pip
value : 3
name : squeak
value : 4
name : wilfred
value : 5
Your variables are:
Line 1,424 ⟶ 1,652:
wilfred = 5
</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}}==
zkl doesn't support adding vars to an existing class but can create a new class with new vars:
<
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</
{{out}}
<pre>
Line 1,440 ⟶ 1,770:
=={{header|Zsh}}==
<
typeset $name=42</
{{omit from|ACL2}}
|