Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for byvalref.vbs

(view source code of byvalref.vbs as plain text)

  1. ' Proof of VBS' byRef parameter passing trap/bug/"feature" by Denis St-Pierre
  2. '
  3. ' If you like to be consistent and re-use the same variable names in functions
  4. ' throughout the same script, you should be aware of this little wrinkle in VBS
  5. '
  6. ' Usually when you call a function in MOST languages, you give it the "contents" of a variable
  7. ' and if you want you can give it a variable "by Reference" to save memory or gain speed if it's
  8. ' contents are large (e.g.: a text file, an array, etc.)
  9. '
  10. ' In VBS, however, when you call a function and pass it a variable, it is "by Reference" by default!
  11. '	IOW: You give the function the actual variable to play with (egg. the container) not the Contents.
  12. ' This means that by default, all variables are effectively "Public" in scope throughout the script
  13. ' EVEN IF YOU DECLARE THE VARIABLE (via Dim) IN THE FUNCTION or SUB
  14. '
  15. ' For proof, play around with the "Function DoStuff" line and you will get different results.
  16. '
  17. ' WORKAROUNDS:
  18. '	1-Use unique variable names in ALL functions and Subs
  19. '	2-Declare Functions and sub that have inputs variables using ByVal as described below
  20. '
  21. ' FYI: ByVal means By Value
  22.  
  23.  
  24. Test()
  25. WScript.Quit(0)	
  26.  
  27.  
  28.  
  29. Function Test()
  30. 	Dim sString	'By doing this here the variable is now "Private"
  31. 			'(or so we are lead to believe)
  32.  
  33. 	sString="hello "
  34. 	MsgBox "sString is =" & sString
  35.  
  36. 	Call DoStuff( sString )  
  37.  
  38. 	MsgBox "sString is =" & sString	'Should still be "hello " if the variable is Private
  39. End Function
  40.  
  41.  
  42. Function DoStuff(sString)		'This is the same as "Function DoStuff(ByRef sString)"
  43. 'Function DoStuff(ByVal sString)	'This will make it that sString variable Private
  44. 'Function DoStuff(ByRef sString)	'This is the same as "Function DoStuff( sString)"
  45. 	sString=sString&sString&sString
  46. 	DoStuff=True
  47. End Function
  48.  

page last modified: 2024-04-16; loaded in 0.0115 seconds