[Closed] declaring local redundant
I am going through the maxscript tutorials that shipped with max and have a very small question.
Why would one want to declare a variable as local ?
I can understand where one would want to declare global variables within statement blocks but if 3dsmax already assumes that variable declarations are local if there is no global designation before it’s name AND if it is within a statement block, declaring a variable as local seems a bit redundant.
As you know, it is optional, but you are strongly encouraged to declare explicitly unless you like long debugging sessions.
The problem is that while some constructs will declare local variables implicitly (for example the counter of a for loop, the argulemts of a function etc,), the USER variables look for existing local variables in higher scopes before checking the global scope. So if you have a local variable in a higher scope, your seemingly local variable might be using a variable that is not as local as you think.
In addition, it is a good precaution against stupid mistakes, because each time you type in a variable name in the Listener, you are implicitly polluting the global name space, and you risk that your implicit local variables would hit one of these global definitions. For example, if you typed in the Listener
test = 123
and then used an implicit local variable called ‘test’ in your script, it would find and use the existing global variable and not create a local one. If another script would also use a variable called ‘test”, you suddenly have two scripts colliding…
And let’s not talk about careless scripters that publish code in global scope, thus potentially causing additinal pollution with implicitly global variables.
So in short: If you want to be SURE that your local variable is local, just tell MAXScript so.
I tend to use implicit locals in short scripts, but lately started forcing myself do declare as local explicitly esp. in large scripts where the same variable name could be used multiple times at different levels.
Hope this helps…
Hi Ryan,
The reason is very simple. Implicit declaration can lead to an error where you need to evaluate the script twice in order for maxscript to initialize the variables correctly.
Light