I have a question about variable scope in VBScript. I know there's the following keywords (from autoitscript.com):
- Dim = Local scope if the variable name doesn't already exist globally (in which case it reuses the global variable!)
- Global = Forces creation of the variable in the Global scope
- Local = Forces creation of the variable in the Local/Function scope
Imagine that I have the following .vbs file:
Dim strPath
strPath = "C:\folder"
DisplayPath strPath
Sub DisplayPath(strPath) 'Does this strPath get it's own local scope?
MsgBox strPath
End Sub
In the function: DisplayPath(strPath)
, is strPath
a local variable? Or do functions/subs have access to the strPath
defined at the top of the main section of the script as a global variable?
Also, what's the point of explicitly using Dim
versus just defining variables as I use them, which is possible in scripting languages?
The
strPath
in theDisplayPath
procedure will be a new variable but not for the reasons you expect, there is subtle problem with your code that will cloud the issue.When calling
Sub
procedure the VBScript syntax does not include parentheses. For example:-the above would result in a syntax error. It should be called:-
Now when there is only one parameter a syntax error does not occur. This is because another use of parentheses is as part of an expression e.g. '(a + b) * c'. In the case of:-
VBScript resolves the "expression"
(strPath)
and pass the result toDisplayPath
. Its this result that gives rise to new storage hold the result the expression.Had you called with
no new created.
However what about this:-
There is still no new storage allocated.
something
will point at the same memory thatstrPath
does.Edit
The code below works:-
The declaration of
strPath
outside of a procedure causes it to have global scope.As to the point of using explicit
Dim
what would happen if the assignment line above looked like this?A new variable called
strPath
would come into existence andstrPath
would remain empty. You should always begin your VBScript files with the line:-This will force you to explicitly
Dim
all variables to be used and will save you hours of debugging time.