0

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?

1 Answer 1

2

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.