Address of a variable: Difference between revisions

(→‎{{header|Commodore BASIC}}: Add example for C64)
Line 552:
=={{header|Commodore BASIC}}==
{{works with|BASIC|7.0 (C-128)}}
The address of a variable in BASIC is readonly, but accessible via the <prett>POINTER</prett> function.
 
<syntaxhighlight lang="basic">100 REM ALLOCATE ALL VARS FIRST SO THEY DON'T MOVE
110 X=123:Y=456:PX=0:PY=0:I=0:T=0
120 PRINT "BEFORE:X ="XCHR$(20)", Y ="Y
130 PX=POINTER(X):PY=POINTER(Y)
140 REM VARS ARE STORED IN RAM BANK 1
Line 565:
190 : POKE PX+I,T
200 NEXT I
210 PRINT "NOWAFTER: X ="XCHR$(20)", Y ="Y</syntaxhighlight>
 
{{works with|BASIC|2.0 (C-64)}}
With older machines, there's no built-in mechanism in BASIC to find a variable's address, but you can use the internal state of the BASIC interpreter to achieve similar results. You have to work around the fact that the interpreter is actively interpreting the running program: for example, you can't store the result of the lookup directly into a variable, because the assignment statement will have changed the pointer to that of the variable being assigned to by the time BASIC executes the <tt>PEEK</tt>.
 
Here's a C-64 version that works the same as the above C-128 program:
 
<syntaxhighlight lang="basic">100 X=123:Y=456
110 SYS 45195 X:POKE 249,PEEK(71):POKE250,PEEK(72)
120 PX=PEEK(249)+256*PEEK(250)
130 SYS 45195 Y:POKE 249,PEEK(71):POKE250,PEEK(72)
140 PY=PEEK(249)+256*PEEK(250)
150 PRINT "BEFORE:X ="XCHR$(20)", Y ="Y
160 FOR I=0 TO 6
170 : T = PEEK(PY+I)
180 : POKE PY+I,PEEK(PX+I)
190 : POKE PX+I,T
200 NEXT I
210 PRINT "AFTER: X ="XCHR$(20)", Y ="Y</syntaxhighlight>
 
It also works on the VIC-20 if you change the <tt>SYS</tt> address to 53387, and with a few other adjustments the same idea will work on other Commodore machines.
 
{{Out}}
 
<pre>X = 123, Y = 456
NOW <pre>BEFORE:X = 456123, Y = 123</pre>456
AFTER: X= 456,Y= 123</pre>
 
=={{header|Common Lisp}}==
1,480

edits