[Gambas-user] Global variables (was: POSSIBLE! bug in while loop)

Tobias Boege taboege at ...626...
Tue Dec 29 18:14:14 CET 2015


On Tue, 29 Dec 2015, Stephen wrote:
> Reading this, in addition to seeing the need for a "Wait", I thought the 
> following;
> 
>    Does putting the desired global variable in a class mean the class 
> needs to be instantiated within the scope of the code example given? i.e.
> 

Strictly speaking, yes.

> PUBLIC GlobalVar as globalVars ' Change the name of the class to keep 
> the var name within the example unchanged.
> 
> within the code of the form which contains the GObtn and exitBtn objects?
> 
> The above would make GlobalVars.iexit visible to all classes outside of 
> the scope of where it was instantiated, so all forms in the project 
> could then see it.
> 

Not really. If Form1 is the form where the Public declaration above is made,
then another class would have to use Form1.GlobalVar.iexit to access the
iexit variable. It cannot directly *see* the GlobalVar object.

> However this can be avoided if the variable "iexit" is declared in a 
> "module" as opposed to a "class". Doing this it instantly becomes global 
> within the scope of the project, requiring only the addition of the 
> "Wait" to process the exitBtn_Click() event and exit the loop.
> 

I take it that your question is "why?". You can think of a module as a class
which has an implicit

  Create Static

statement in its header and where every symbol is implicitly Static. [ Note
that you *can* instantiate a module using New, i.e. it is not implicitly
Create Private, but you cannot do anything with an instance of a module
because every symbol is static (accessing any symbol from the instance
throws a "<class>.<symbol> is static" error). ]

Read about the Create Static statement here[0]. To explain my first comment
above: You need to have an object of your global variables class available
to use those variables. But employing Create Static you can basically make a
class name (and class names are project-global) refer to an object (the
automatic instance of that class). The result is that you have a globally
accessible object.

Regards,
Tobi

[0] http://gambaswiki.org/wiki/lang/createstatic

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk




More information about the User mailing list