Site Tools


Differences

This shows you the differences between two versions of the page.

Link to this comparison view

developer:scriptsamples:hoisting [2015/09/14] (current)
Line 1: Line 1:
 +======Variable Hoisting in RhinoScript======
 +> **Developer:​** [[developer:​rhinoscript|RhinoScript]]
 +> **Summary:​** //Some notes on variable scoping in VBScript.//
 +
 +=====Question=====
 +In VBScript, the following code doesn'​t work, which I understand:
 +
 +<code vb>
 + ​Option Explicit
 + s = "​Hello"​
 +</​code>​
 +
 +However, the following code works fine:
 +
 +<code vb>
 + ​Option Explicit
 + s = "​Hello"​
 + Dim s
 +</​code>​
 +
 +Why can we use a variable before declaring it in VBScript?
 +
 +=====Answer=====
 +If you think that the above looks odd, do you think this looks normal?
 +
 +<code vb>
 + Dim s
 + s = Foo(123)
 +
 + ​Function Foo(x)
 +   Foo = x + 345
 + End Function
 +</​code>​
 +
 +Here the function is being used before it is declared. Similarly, variables can be used before they are declared. The behaviour is by design. Variable declarations and functions are logically "​hoisted"​ to the top of their scope in VBScript.
 +
 +Also, declaring a variable twice in the same script block is illegal, but redefinition in another block is legal. Procedures may be redeclared at will except if the procedure is in a class, in which case redeclaration is illegal.
 +
 +Did you know that this is legal in VBScript?
 +
 +<code vb>
 + s = Foo(123)
 + If Blah Then
 +   ​Function Foo(x)
 +     Foo = x + 345
 +   End Function
 + End If
 +</​code>​
 +
 +This is not recommended,​ but it is legal.
 +
 +=====More information=====
 +
 +<code vb>
 + Dim i
 + For i = 1 To 2
 +   ​Rhino.Print c
 + Next
 + Const c = 10
 +</​code>​
 +
 +And this works:
 +
 +<code vb>
 + For i = 1 To 2
 +   ​Rhino.Print c
 +   Dim i
 + Next
 + Const c = 10
 +</​code>​
 +
 +But, this fails with a "name redefined"​ error:
 +
 +<code vb>
 + For i = 1 To 2
 +   ​Rhino.Print c
 +   Const c = 10
 +   Dim i
 + Next
 +</​code>​
 +
 +In VBScript:
 +
 +  * **Variable** declarations are logically hoisted to the top of the scope.
 +  * **Constants** are evaluated at code compilation time; the constants'​ values are injected into the code.
 +
 +\\
 +
 +{{tag>​Developer RhinoScript}}
  
developer/scriptsamples/hoisting.txt ยท Last modified: 2015/09/14 (external edit)