ByRef and ByVal in vbscript

Here is an interesting post by Eric Lippert explaining how to pass variables to vbscript subroutines and functions without using ByRef or ByVal:

Sub Bar(x) 
End Sub 
Sub Baz(a, b) 
End Sub 
Function Foo(y) 
End Function 
z = 123 
n = Foo(z)         ' legal, passes z by reference 
n = Foo((z))       ' legal, passes z by reference 
'n = Foo z         ' illegal, parens required 
Foo z              ' legal, passes z by reference 
Foo(z)             ' legal, passes z by value 
'Call Foo z        ' illegal, parens required 
Call Foo(z)        ' legal, passes z by reference 
Call Foo((z))      ' legal, passes z by value 
'n = Bar(z)        ' illegal, bar is not a function 
Bar z              ' legal, passes z by reference 
Bar(z)             ' legal, passes z by value 
Call Bar(z)        ' legal, passes z by reference 
Call Bar((z))      ' legal, passes z by value 
Baz z, z           ' legal, passes z by reference 
Baz (z), (z)       ' legal, passes z by reference 
'Baz(z,z)          ' illegal, can't use parens 
Call Baz(z, z)     ' legal, passes z by reference 
Call Baz((z), (z)) ' legal, passes z by value 
'Call Baz z, z     ' illegal, parens required

So basically if you want to pass a variable by value you need to wrap it in an extra set of brackets


Posted on Thursday, May 5, 2011 11:19:00 AM GMT by Tao
A couple of examples above appear to be wrong:

n = Foo((z)) ' legal, passes z by reference
Baz (z), (z) ' legal, passes z by reference

Z would get passed by value in both of these examples, not by reference.

Post a comment