GENERATE/PREV.gifGENERATE/NEXT.gif

Scoping and Extent

When you declare a local variable, you can re-use the same name as a global variable or local variable in an enclosing block or function. If you do this, the newly declared local variable hides the outer variables with the same name, any reference to that variable identifier later in the local variable's block refers to the new local variable. At the end of the local's block, the next outer variable becomes visible again. This visibility scheme is called lexical scoping and the segment of code in which a particular variable is visible is called its scope.

Example:

global foo = 23

if x > y then

(

local baz = foo + 1,      -- gets the global foo

foo = y - 1      -- declares 1st local foo, hides global foo

$obj.pops.x = foo      -- gets 1st local foo

if (foo > 0) then

(

local a, b, foo = y - x      -- a nested 2nd local foo, hides 1st local

a = sin foo      -- get 2nd local foo

print a

)      -- leave scope

$obj2.pos.x = foo - 1.5      -- back to 1st local foo

)      -- leave scope

print foo      -- back to global foo

This might seem a strange way of over-using a single variable name, but in large programs, however, these scoping rules can be quite useful.

Extent

Another important property of variables is their extent. Extent refers to the length of time that a variable's value is accessible. In the case of global variables, their extent lasts for the entire MAX session, matching its scope, or visibility, which covers all of the MAXScript code you run while you are using MAX.

On the other hand, local variables have a scope that is limited to the block they are declared in, and their extent also lasts for the block they are in.