Address of a variable: Difference between revisions

(→‎{{header|Commodore BASIC}}: Add example for C64)
Line 567:
210 PRINT "AFTER: X="XCHR$(20)",Y="Y</syntaxhighlight>
 
{{works with|BASIC|2.0 (VIC-20, 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 canHere't store the result of the lookup directly intos a variable,VIC-20/C-64 because the assignment statement will have changed the pointer toversion that ofworks the variablesame being assigned to byas the timeabove BASICC-128 executes the <tt>PEEK</tt>.program:
 
<syntaxhighlight lang="basic">100 X=123PEEK(71)+256*PEEK(72):YPX=456X:X=123
Here's a C-64 version that works the same as the above C-128 program:
140110 PYY=PEEK(24971)+256*PEEK(25072):PY=Y:Y=456
 
150120 PRINT "BEFORE:X ="XCHR$(20)", Y ="Y
<syntaxhighlight lang="basic">100 X=123:Y=456
160130 FOR I=0 TO 6
110 SYS 45195 X:POKE 249,PEEK(71):POKE250,PEEK(72)
120140 : T PX= PEEK(249)PY+256*PEEK(250I)
130150 SYS: 45195 Y:POKE 249,PEEK(71):POKE250PY+I,PEEK(72PX+I)
190160 : POKE PX+I,T
140 PY=PEEK(249)+256*PEEK(250)
200170 NEXT I
150 PRINT "BEFORE:X ="XCHR$(20)", Y ="Y
210180 PRINT "AFTER: X ="XCHR$(20)", Y ="Y</syntaxhighlight>
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.
 
They same idea should work on other Commodore computers as well, though at least the address being <tt>PEEK</tt>ed will have to change.
{{Out}}
 
1,480

edits