Execute! II

Happy New Year!

When last we spoke, I’d given you some code that doesn’t work quite right:

Const pi = 3.1416
WScript.Echo Main()
Function Main()
 Const r = 2.5
 Dim result
 Dim str
 str = “result=pi*(r*r)”
 ExecuteGlobal str
 Main = result
End Function

Did you see why? ExecuteGlobal is executing the contents of variable str in the global scope. However, the constant r doesn’t exist in the global scope – it’s local to the function Main(). In the global scope, then, VBScript has to implicitly declare a variable r and give it the default value of zero. The result of the mathematical expression is therefore zero, since anything multiplied by zero results in zero. Had I put Option Explicit in there, I would have gotten an error when running ExecuteGlobal, since I would have been executing code that used an undeclared variable – at least, undeclared in the scope in which the code executed.

There’s a second problem, too, which is that when ExecuteGlobal runs, a variable named “result” is being implicitly declared in the global scope, because that expression is using the variable “result” in the global scope, where the variable hasn’t been explicitly declared. Again, Option Explicit would have generated an error here. The function’s copy of “result” remains at zero, because nothing in the function’s local scope ever assigned a value to the local version of “result.” This is a big reason to NEVER re-use variable names in the global scope and the local scope.

Here’s another one to examine:

Const pi = 3.1416
r = 0
WScript.Echo Main()
Function Main()
 r = 2.5
 Dim result
 Dim str
 str = “result=pi*(r*r)”
 Execute str
 Main = result
End Function

And its twin:

Const pi = 3.1416
r = 0
WScript.Echo Main()
Function Main()
 r = 2.5
 Dim result
 Dim str
 str = “result=pi*(r*r)”
 ExecuteGlobal str
 Main = result
End Function

Do you see what’s logically wrong, here? One of these will return zero; the other will return an actual value. Why? Well, there are two good reasons: More details next Tuesday…