LoginLogin

Is there a quick way to 'redimension' arrays?

Root / Programming Questions / [.]

SquareFingersCreated:
In some dialects of Basic, after an array is declared with something like DIM A$[10], it is possible to change the number of subscripts in the array with a command like REDIM A$[20], or even REDIM A$[5] if you want to reduce the size. SmileBasic arrays are not of fixed size. SHIFT, UNSHIFT, PUSH and POP all alter the size of an array by 1 element. If I want to resize an array to, say, zero, is there any way to do that other than repeated POPs or SHIFTs?

can't you just use DIM again?

Array variables are, in essence, references. So if you assign another array B$ to A$, then the name A$ will reference the same array that B$ references, and the array that A$ previously referenced will be deleted if no other name is referencing it. Then if B$ gets deleted (as in returning from a function if B$ was a local variable), then A$ will be the only reference to the new array. SWAP can also be used to exchange two array references. You can also return an array reference from a function. So it's possible to do:
DEF REDIM$(A$,N%)
 DIM B$[N%]
 COPY B$,A$,MIN(N%,LEN(A$))
 RETURN B$
END

DIM A$[10]
A$=REDIM$(A$,20)
Edit: Forgot to put the $ on the function call

Good solution, calc84maniac. Amazingly, it doesn't even cause a memory leak.

The function also works with the following:
DIM B%[10]
B%=REDIM$(B%,20)
B%[1]="Hello"
PRINT B%[1]
It appears there is a 'type' for variables and values, which is simply generic 'array', and there are not different types for 'array of string', 'array of integer', and 'array of floating-point'. EDIT: Even the number of dimensions can change. The REDIM function can be adjusted to output a 2-dimensional array, or 3-dimensional array; the number of dimensions in the returned array need not match the number of dimensions of the array variable being assigned to. EDIT: But, if an array is SAVEd to a DAT file, and the array is two-dimensional, the array used to re-LOAD it must also be two dimensional. It need not be the same size in either dimension, the size is adjusted to that of the array SAVEd, but, it must have the same number of dimensions as the array SAVEd.

That's a good idea! This is what I need to improve my Wav Recorder project. It's a shame that you can't name an array with a string variable. That would make copying and pasting array names much easier.

Actually, I recently found out that there is a way to access variables given the string of its name, by using VAR() as a function. So for example, you could do something like VAR("A")[0]=20 as the equivalent of A[0]=20. But you would still have to define each of the array names individually with DIM, as far as I can tell. VAR() will only access variables that have already been defined.

WHY would they not document this?