Execute!

Jeff Hicks and I have been having some fun with the VBScript Execute() method, as Jeff’s been writing about it for VBScript and WSH Core: TFM? this week. Here’s some sample code:

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

Do you know what this does? Follow along: Obviously, I’m declaring two constants. These exist in the global scope. Then I call a function, Main(), and display its result. Within the function, I’m declaring two variables: Result and str. Str is being set equal to an actual VBScript statement, and the Execute method is executing that. The result variable then contains the result of the mathematical equation, which is returned as the function’s output. Try it.

Now consider this minor modification:

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

This will work identically. All I’ve done is move the r constant into the function. That makes r local to the function, meaning the value of r can’t be seen outside the function. However, since the code utilizing the r constant is executing within the function, it all works fine.

One more change:

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

Do you see why this won’t work? Stay tuned until next Tuesday.