Address of a variable: Difference between revisions

Content added Content deleted
(→‎{{header|Commodore BASIC}}: Add example for C64)
Line 567: Line 567:
210 PRINT "AFTER: X="XCHR$(20)",Y="Y</syntaxhighlight>
210 PRINT "AFTER: X="XCHR$(20)",Y="Y</syntaxhighlight>


{{works with|BASIC|2.0 (C-64)}}
{{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 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>.
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. Here's a VIC-20/C-64 version that works the same as the above C-128 program:


<syntaxhighlight lang="basic">100 X=PEEK(71)+256*PEEK(72):PX=X:X=123
Here's a C-64 version that works the same as the above C-128 program:
110 Y=PEEK(71)+256*PEEK(72):PY=Y:Y=456

120 PRINT "BEFORE:X ="XCHR$(20)", Y ="Y
<syntaxhighlight lang="basic">100 X=123:Y=456
130 FOR I=0 TO 6
110 SYS 45195 X:POKE 249,PEEK(71):POKE250,PEEK(72)
120 PX=PEEK(249)+256*PEEK(250)
140 : T = PEEK(PY+I)
130 SYS 45195 Y:POKE 249,PEEK(71):POKE250,PEEK(72)
150 : POKE PY+I,PEEK(PX+I)
160 : POKE PX+I,T
140 PY=PEEK(249)+256*PEEK(250)
170 NEXT I
150 PRINT "BEFORE:X ="XCHR$(20)", Y ="Y
180 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}}
{{Out}}