B4R Question Scope of Global Objects

JMB

Active Member
Licensed User
Longtime User
Hi there

I am just trying to understand the scope of global objects when using B4R with an ESP8266 chip.

I understand that global variables are treated as constants in B4R, but that global objects are treated slightly differently.

For that reason I tried this code in order to make a Global object.
B4X:
Sub Process_Globals
    Dim UniqueID(1) As Object
    Private bc As ByteConverter
End Sub

Private Sub AppStart
    UniqueID(0) = bc.HexFromBytes(GetMacAddress)
    Log("    MAC address is: ", UniqueID(0))
End Sub

If I call ANY Sub from within AppStart - and any Sub from within THAT Sub, then UniqueID appears to hold its value.

However, if I try to use UniqueID from any other sub that is NOT called within the AppStart sub, then UniqueID loses its value.

I am a little confused because having read this from Erel....

Memory is a big issue in Arduino.

1. The available RAM is very small compared to other platforms. For example the Uno has 2k of RAM.
2. There is no sophisticated heap management which means that usage of dynamic memory should be avoided.
3. Programs are expected to run for a long time with zero memory leaks.

There are two types of variables in B4R: local variables and global variables.

Local variables are always created on the stack. This means that any object created in a sub, other than Process_Globals, will be destroyed when the sub ends (this is not the case in other B4X tools).

Global objects, which are objects created in Process_Globals, are not stored in the stack and will always be available.
Note that global variables, except of primitives, behave as constants. You cannot redim them and they cannot be reassigned.

I understand that this means I can use an object as a Global variable, but I am unclear as to why it loses its value...

Any help would be gratefully appreciated.

JMB
 

kolbe

Active Member
Licensed User
Longtime User
The way I understand this is that globals are only constant if they are not primitives or you define them as constants. Any global primitive would work just as you would expect a global to work. This needs to be so because the size of the data allocated for globals does not change during runtime. So and integer value can be a global and change because 2 bytes have been allocated and the value of those two bytes can change during runtime. A string however cannot be a global because depending on the value of the string, the number of bytes needed to hold the string will change and this can't happen to a global.

In your case above the value of the object exists as long as AppStart is executing. As soon as it finishes the value is lost. I'm not sure how an object is stored but I would guess it is just a pointer to a value that gets created in the current sub and when the sub finishes the value is gone.

For storing non primitives as globals you have to use something like this.
 
Upvote 0
Top