In VBScript, there are two ways values can be passed to functions: by value or by reference.
Lets see a quick example to see how parameters are passed by value.
Function func_Value( ByVal var)
var = var + 1
End Function
Dim x
x = 10
func_Value x
When you run the above code in your QTP editor, you will get the output as 10. What has actually happened is when you have passed the argument by value, a copy of the variable x is passed to the variable "var". Inside the function, this "var" variable gets incremented to 1 and when the function ends, this variable gets destroyed as it was a local variable. So no change is being done to our global variable "x".
In order to increment the global variable x, we need to make a very small change in our VBScript code. Instead of the ByVal keyword, all we need to do is to change it to ByRef keyword.
The modified code would be:
Function func_Value( ByRef var)
var = var + 1
End Function
Dim x
x = 10
func_Value x
Now on executing the above code, the output would be 11. The reason being, the local variable "var" is pointing to the same location in memory as the variable x. So whatever changes we will make through the variable "var", they will be reflected in variable "x" also. This technique is called passing values by reference.
In the above code, if we omit the ByRef keyword, still the arguments would be passed by reference.
For example:
Function func_Value(var)
var = var + 1
End Function
Dim x
x = 10
func_Value x
Thursday, December 29, 2011
VBScript Passing Values ByVal ByRef
Wednesday, December 28, 2011
VBScript GetRef Function
VBScript GetRef function returns a reference to a sub procedure or a function.
Copy the below VBScript code in QTP editor and see the output:
Function ShowMsg(ByVal sName)
ShowMsg = "Hello, " + sName
End Function
Set fnPtr = GetRef("ShowMsg")
After using GetRef, fnPtr actually contains a reference of our function "ShowMsg". It means, now onwards both the function and its reference will do the same thing.
Example, see the below code
Msgbox fnPtr("HP_QTP")