Difference between revisions of "Globals"

From MiniScript Wiki
Jump to navigation Jump to search
m
Line 3: Line 3:
 
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.
 
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.
+
So, when you want to create or update a global variable inside a function, the '''globals''' keyword must be used on the left-hand side of the assignment.
  
 
See also: [[locals]]; [[outer]].
 
See also: [[locals]]; [[outer]].

Revision as of 21:50, 16 June 2022

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 on the left-hand side of the assignment.

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.