Google suggested the "error trapping" method (see below).
Is that how we do it in QB64PE?
Is that how we do it in QB64PE?
Quote:In QB64PE, there is no direct function or property to determine the number of dimensions of an array at runtime, unlike some other languages.
However, you can achieve this by attempting to access UBOUND with increasing dimension indices and handling the ON ERROR condition.
Here's a method using ON ERROR:
Code: (Select All)DIM a(2, 2, 2) AS INTEGER ' Example: a 3-dimensional array
DIM SHARED numDimensions AS INTEGER
ON ERROR GOTO ErrorHandler
CALL CountDimensions(a())
PRINT "Number of dimensions: "; numDimensions
END
ErrorHandler:
IF ERR = 9 THEN ' Subscript out of range error
RESUME NEXT ' Continue execution after the error
ELSE
PRINT "An unexpected error occurred: "; ERR
END
END IF
SUB CountDimensions (arr() AS INTEGER)
numDimensions = 0
DO
numDimensions = numDimensions + 1
' Attempt to get the upper bound of the current dimension
' If this dimension doesn't exist, an error will occur
dummy = UBOUND(arr, numDimensions)
LOOP
END SUB
Explanation:
DIM SHARED numDimensions AS INTEGER:
Declares a shared variable to store the count of dimensions, accessible by the CountDimensions sub-procedure.
ON ERROR GOTO ErrorHandler:
Sets up error handling. If an error occurs, the program jumps to the ErrorHandler label.
CALL CountDimensions(a()):
Calls the sub-procedure to determine the dimensions, passing the array.
SUB CountDimensions (arr() AS INTEGER):
Initializes numDimensions to 0.
The DO...LOOP attempts to get the UBOUND of progressively higher dimensions (UBOUND(arr, 1), UBOUND(arr, 2), etc.).
If UBOUND is called with a dimension index that doesn't exist, a "Subscript out of range" error (error code 9) will occur.
ErrorHandler::
Checks if the error is "Subscript out of range" (ERR = 9).
If it is, RESUME NEXT is used to continue execution from the statement immediately following the one that caused the error (which is the dummy = UBOUND(...) line). This effectively stops incrementing numDimensions at the correct value.
If it's a different error, it prints the error code and ends the program.
This method leverages QB64PE's error handling to indirectly determine the number of dimensions by detecting when an invalid dimension index is accessed.

