Global Variables

The ‘global’ statement is used to declare global variables. For example:

macro SomeFunction()
{
    global last_count
    ...
}

A variable that is declared with the ‘var’ statement, or created by assignment is considered local to the function that contains the statement. However, the ‘global’ statement is a way to declare a variable whose scope is global instead of local. That means you can access it from multiple functions.

When the ‘global’ statement is encountered, the variable is entered into the global-scope variable table. The variable is initialized to 'nil'. This example shows how you might declare and use a global counter variable:

macro SomeFunction()
{
    global last_count

    // this initializes it the first time through
    if last_count == nil last_count = 0
    ...
}

Global variables live as long as the Source Insight session. That is, they can contain information between invocations of macro or event functions. They are lost when you exit Source Insight.

The ‘global’ statement is executed when it is encountered, and it must be in the execution path of your statements. You should put the ‘global’ statement inside of a function.

Global variables are useful for adding counters, and other persistent state. They cannot hold any kind of handle, because all handles are destroyed when a macro finishes. So, for example, this will not work:

global hbuf
hbuf = OpenBuf("abc.txt")

In the above example, the hbuf variable will contain a bogus handle as soon as this macro finishes.