Variables: Difference between revisions

1,254 bytes added ,  1 month ago
m
 
(3 intermediate revisions by 3 users not shown)
Line 2,388:
=={{header|J}}==
 
<syntaxhighlight lang="j">val=. 0</syntaxhighlight>
val=. 0
</syntaxhighlight>
 
J has two assignment operators. The =. operator declares, initializes, assigns, etc. a local variable. The =: operator does the same for a "global" variable.
 
<syntaxhighlight lang="j">fun =: 3 :0
fun =: 3 :0
val1 =: 0
val1 =. 2
Line 2,403 ⟶ 2,406:
0
val2
|value error</syntaxhighlight>
</syntaxhighlight>
 
Note that the language forbids assigning a "global" value in a context where the name has a local definition.
 
<syntaxhighlight lang="j">fun1 =: 3 :0
fun1 =: 3 :0
val3=. 0
val3=: 0
)
fun1''
|domain error</syntaxhighlight>
</syntaxhighlight>
 
But the purpose of this rule is to help people catch mistakes. If you have reason to do this, you can easily set up another execution context.
 
<syntaxhighlight lang="j">fun2 =: 3 :0
fun2 =: 3 :0
val4=. 0
3 :'val4=:y' y
)
fun2 ''</syntaxhighlight>
</syntaxhighlight>
 
Variables are referred to by name, and exist in locales (which may be used as classes, closures or other stateful references).
Line 4,615 ⟶ 4,623:
see Msg + nl
</syntaxhighlight>
 
=={{header|RPL}}==
A global variable is declared with the <code>STO</code> instruction after the variable name.
A local variable, which disappears at end of execution, is declared with the <code>→</code> instruction before the variable name, which is idiomatically in lowercase.
in both cases, the variable is initialized with the value at stack level 1, whatever its type.
123 'V' STO
123 → v
A new value can then be assigned with the <code>STO</code> instruction:
"AZ" 'V' STO
"AZ" 'v' STO
A variable can contain any type of data, which can change without need for reinitialization, as shown above.
It is possible to add, substract, multiple, divide... the content of stack level 1 to a variable with specific instructions, resp. <code>STO+, STO-, STO*, STO/</code>...
If the variable contains a list, STO+ will append or prepend the content of stack level 1, according to the order of the arguments:
456 'MYLIST' STO+ <span style="color:grey">@ prepend</span>
'MYLIST' 456 STO+ <span style="color:grey">@ append</span>
<code>STO-</code> and <code>STO/</code> have the same versatility:
123 'V' STO- <span style="color:grey">@ V ← 123 - V</span>
'V' 123 STO- <span style="color:grey">@ V ← V - 123</span>
 
=={{header|Ruby}}==
Line 5,408 ⟶ 5,434:
 
Here are a few examples.
<syntaxhighlight lang="ecmascriptwren">var a // declares the variable 'a' with the default value of 'null'
a = 1 // initializes 'a'
a = "a" // assigns a different value to 'a'
1,150

edits