AhmedWas
AhmedWas

Reputation: 1277

How to initialize multiple variables together?

I need to initialize several variables with the same value in VBScript. The only way I can find is for example x = 5 : y = 5 : z = 5. Is there a way similar to x = y = z = 5?

Upvotes: 3

Views: 6915

Answers (2)

MC ND
MC ND

Reputation: 70933

The construct x = y = z = 5 works in languages where the assignment expressions return the value assigned, that is used in the previous assignment, ....

But in VBScript the assignment expressions don't return any value so you can't do it.

But if assigning value to the variables in only one line with the value indicated only once is a requirement, you can use the standard three separated statements

x = 5 : y = x : z = x

or do something like (and yes, I know, it is not efficient and it is not pretty, it just does the work)

Option Explicit

Function S(ByRef variable, value)
    If IsObject( value ) Then 
        Set variable = value
        Set S = value
    Else 
        variable = value
        S = value
    End If
End Function

Dim x, y, z
    Call S(x, S(y, S(z, 5)))

    WScript.Echo x & " " & y & " " & z 

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200303

VBScript doesn't support multiple assignments. A statement

x = y = z = 5

would be evaluated like this (pseudocode using := as assignment operator and == as comparison operator to better illustrate what's happening):

x := ((y == z) == 5)
x := ((Empty == Empty) == 5)
x := (True == 5)
x := False

As a result the variable x will be assigned the value False while the other variables (y and z) remain empty.

Demonstration:

>>> x = y = z = 5
>>> WScript.Echo TypeName(x)
Boolean
>>> WScript.Echo "" & x
False
>>> WScript.Echo TypeName(y)
Empty
>>> WScript.Echo TypeName(z)
Empty

The statement

x = 5 : y = 5 : z = 5

isn't an actual multiple assignment. It's just a way of writing the 3 statements

x = 5
y = 5
z = 5

in a single line (the colon separates statements from each other in VBScript).

Upvotes: 5

Related Questions