Forum
Can values assigned with DIM be reinitialized? - Printable Version

+- Forum (https://www.boriel.com/forum)
+-- Forum: Compilers and Computer Languages (https://www.boriel.com/forum/forumdisplay.php?fid=12)
+--- Forum: ZX Basic Compiler (https://www.boriel.com/forum/forumdisplay.php?fid=11)
+---- Forum: How-To & Tutorials (https://www.boriel.com/forum/forumdisplay.php?fid=13)
+---- Thread: Can values assigned with DIM be reinitialized? (/showthread.php?tid=888)



Can values assigned with DIM be reinitialized? - Alessandro - 07-25-2019

At the start of a program, some variables are declared and their values assigned accordingly, e.g.:

Code:
start:

  DIM year AS UBYTE = 56

  DIM pre AS BYTE = 100

  DIM stru(3,9) AS UBYTE => {{1,0,0,1,0,1,0,1,0}, {0,3,3,0,4,0,4,0,5}, {0,30,30,0,60,0,50,0,70}}

While the program is running, some of these values are changed:

Code:
year = year + 10

  stru(2,9) = 1

etc.

At the end, when the program should go back to the start

Code:
end:

  GOTO start

variables retain the values they held at that time instead of being reinitialized. To do that, I must explicitly insert a series of LET instructions after the DIMs, e.g.

Code:
DIM year AS UBYTE

DIM pre AS BYTE

DIM stru(3,9) AS UBYTE

...

year = 56

pre = 100

  RESTORE strudata

FOR n = 1 TO 3
  FOR m = 1 TO 9
     READ stru(n,m)
  NEXT m
NEXT n

which is pretty annoying as well as making the program use more memory.

Is there any way to make DIM reinitialize variables?


Re: Can values assigned with DIM be reinitialized? - boriel - 07-29-2019

No, there's no way for this, because when you declare with DIM a variable you're just declaring it (reserving memory) with a default value. So using a second assignation to reinitialize it, is not such a memory waste.

For arrays, the classic way to to that is to use READ, DATA, RESTORE to populate the array.
Other (faster) way is to initialize the array the way you did in a temporary one, and assign it upon start:

Code:
DIM struCopy(3,9) AS UBYTE => {{1,0,0,1,0,1,0,1,0}, {0,3,3,0,4,0,4,0,5}, {0,30,30,0,60,0,50,0,70}}

start:
   stru = struCopy : REM copies the array into stru

...

This way is the recommended and takes the same memory (any default value must be saved somewhere to be copied again upon re-start).
A more elegant way is to use REDIM (which is equivalent to Sinclair BASIC DIM in the sense it's executed everytime the executions reaches its point). I'm working on it, but it's not yet finished.