Forcing an array to exist.

Discussions about the BBC BASIC language, with particular reference to BB4W and BBCSDL
Flatlander
Posts: 19
Joined: Fri 08 Jul 2022, 02:47
Location: England

Forcing an array to exist.

Post by Flatlander »

There is a webpage “Forcing a variable to exist”:
https://www.bbcbasic.net/wiki/doku.php? ... to_20exist

Out of curiosity:

How would I best do the same for an array?
array() = array()
array() += 0
won’t work because of the necessary DIM statement when creating an array.

I found a solution suitable for my needs:
Try one of the above solutions in a PROC, and create the array in some local ERROR code if it fails.

But what if I want to force several arrays to exist? The ERROR code won’t know which arrays need to be created.

Is there a best-practice for this?
Can it be achieved outside of a PROC/FN?
Finishing that game Any Decade Now™
Richard Russell
Posts: 366
Joined: Tue 18 Jun 2024, 09:32

Re: Forcing an array to exist.

Post by Richard Russell »

Flatlander wrote: Sun 27 Apr 2025, 05:46 How would I best do the same for an array?
A couple of ways to 'force' an array to exist are to return its address:

Code: Select all

      address%% = ^array()
or to make it LOCAL or PRIVATE (which of course only works inside a function or a procedure):

Code: Select all

      LOCAL array()
Both will create an undeclared array, that is an array which exists but which doesn't (yet) have any dimensions. You can determine that by testing the array's pointer:

Code: Select all

      pointer%% = PTR(array())
This will be zero (or one) in the case of an undeclared array. The only way to give an array dimensions is to use DIM.

An additional (but probably less useful) way to create an array is to specify it as a RETURNed parameter:

Code: Select all

      PROCtest(array())
      END
      
      DEF PROCtest(RETURN a())
      ENDPROC