Reputation: 1186
VBScript has two syntaxes for setting a variable
Primitives such as String and Integer are set as
primitive_var = 3
While objects are set as
Set my_object = some_object
I have a function call that could return either. I can check for the type as follows
If VarType(f(x, y)) = vbObject Then
Set result = f(x, y)
Else
result = f(x, y)
End If
However this wastes a function call. How can I do this with only one call to f?
Upvotes: 0
Views: 347
Reputation: 38765
You could use a Sub that assigns to a variable, using Set for objects:
Option Explicit
' returns regexp or "pipapo" (probably a design error,
' should be two distinct functions)
Function f(x)
If x = 1 Then
Set f = New RegExp
Else
f = "pipapo"
End If
End Function
' assigns val to var nam, using Set for objects
' ByRef to emphasize manipulation of var nam
Sub assign(ByRef nam, val)
If IsObject(val) Then
Set nam = Val
Else
nam = Val
End If
End Sub
Dim x
assign x, f(1) : WScript.Echo TypeName(x)
assign x, f(0) : WScript.Echo TypeName(x)
output:
cscript 27730273.vbs
IRegExp2
String
but I would prefer to have two distinct functions instead of one f().
Upvotes: 2