I have a question about variable scope in VBScript. I know there\'s the following keywords (from autoitscript.com):
The strPath
in the DisplayPath
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:-
Sub MyProc(Param1, Param2)
'' # Do stuff
End Sub
MyProc("Hello", "World")
the above would result in a syntax error. It should be called:-
MyProc "Hello", "World"
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:-
DisplayPath(strPath)
VBScript resolves the "expression" (strPath)
and pass the result to DisplayPath
. Its this result that gives rise to new storage hold the result the expression.
Had you called with
DisplayPath strPath
no new created.
However what about this:-
Sub DisplayPath(something)
MsgBox something
End Sub
There is still no new storage allocated. something
will point at the same memory that strPath
does.
Edit
The code below works:-
Dim strPath
strPath = "c:\folder"
Display
Sub Display()
MsgBox strPath
End Sub
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?
strPath = "c:\folder"
A new variable called strPath
would come into existence and strPath
would remain empty. You should always begin your VBScript files with the line:-
Option Explicit
This will force you to explicitly Dim
all variables to be used and will save you hours of debugging time.