7.4.6 Embedded array - Embedded array

Dynamic arrays are real Gambas objects, while embedded arrays are a way to access part of an object as an array. In this case, a memory block is allocated to the array content - exactly where the embedded array was declared object-related. The bottom line is that in gambas, all properties of an object are usually accessible via references, i. e. outside of this object. This is not the case with embedded arrays (hence the name). These arrays get a fixed value when the class is defined and are then stored directly as a memory block in the description of the class as it is available to the interpreter.

Syntax for an embedded array:

[ STATIC ] { PUBLIC | PRIVATE } Identifier [ Array dimensions ... ] AS NativeDatatype

Since embedded arrays are not objects, but gambas can only work with objects, you go a different way and create a temporary object that shows the interpreter how to work with such arrays without them being full-fledged objects. Embedded arrays cannot be declared as local variables, because each value on the Gambas stack (the local variables are located there) can only consume a certain memory area (32 bytes on a 64-bit system) and arrays can be larger!

The special position of embedded arrays is also reflected in an article by Emil Lenngren. He writes: “Embedded arrays consume less memory because their data is directly allocated in the class structure. But they are slower because a wrapper object must be created for each access. <colour red/white>I recommend that you do not use embedded arrays. </colour>You are useful when you need to create a structure that contains an array that you want to pass to an external C function later - but not otherwise.”

Similarly, Benoît Minisini commented: “Embedded arrays were introduced to have the ability to imitate a memory structure declared in a C library (In C, all structural elements are allocated as blocks within the structure - which is not normally the case in Gambas - except for embedded arrays). Otherwise there's no real reason to use it.”

Embedded arrays are - as emphasized above by Lenngren and Minisini - marginal phenomena.

Nevertheless, an example shows the (formal) use of an embedded array:

PUBLIC embArray[3, 3, 3] As Integer
...
Public Sub btnShowEmbeddedArray_Click()
  Dim i, ii, iii As Integer
' Dim embArray[3, 3, 3] As Integer ' → ERROR!

  For i = 0 To 2
    For ii = 0 To 2
      For iii = 0 To 2
        Print "[ "; i; " | "; ii; " | "; iii; " ]"; " = ";
        embArray[i, ii, iii] = i * 9 + ii * 3 + iii
        Print embArray[i, ii, iii]
      Next
    Next
  Next

End ' btnShowEmbeddedArray_Click()

Output in the IDE console:

[ 0 | 0 | 0 ] = 0
[ 0 | 0 | 1 ] = 1
[ 0 | 0 | 2 ] = 2
[ 0 | 1 | 0 ] = 3
...
[ 1 | 0 | 0 ] = 9
[ 1 | 0 | 1 ] = 10
[ 1 | 0 | 2 ] = 11
...
[ 2 | 2 | 0 ] = 24
[ 2 | 2 | 1 ] = 25
[ 2 | 2 | 2 ] = 26