Globals

From MiniScript Wiki
Revision as of 15:24, 3 June 2020 by JoeStrout (talk | contribs) (added "See also")
Jump to navigation Jump to search

globals is a built-in keyword that references variables at the global scope. Any assignment outside of any function creates (or updates) an entry in the globals map.

Inside a function, an unqualified assignment (i.e. an assignment to an identifier that does not follow a dot — like x rather than foo.x) creates a local variable. Local variables exist only within the function where they are created, and disappear as soon as the function exits. This is true even if there happens to already be a global variable of the same name.

So, when you want to create or update a global variable inside a function, the globals keyword must be used.

See also: locals; outer.

Example

The check function below compares its parameter to a global variable. The comparison does not need the globals keyword, because it's only reading the value (and there is no local variable of the same name). But when it updates the global value, it has to use globals.

lastValue = null
check = function(someValue)
    if someValue != lastValue then
        print "The value is now: " + someValue
        globals.lastValue = someValue  // <--- Note use of globals
    end if
end function

x = 0
while true
    check round(x)
    x = x + 0.1
    wait 0.1
end while

Also note that the while loop at the end is at the global scope, so it does not need to use 'globals at all; globals and locals are the same in this case.