2

Perhaps I'm missing something, but it annoys me that VBScript seems to read all OR condtions. For example, I'd like to do something like this:

If (oFS.FileExists(sFileLoc) = False) Or (sNewText <> oFS.OpenTextFile(sFileLoc).ReadAll) Then

Now I get an error that the file doesn't exist because of the second condition. I was hoping that if the file doesn't exist VBScript would skip immediately to the result, and if it does, it checks the second condition.

Am I right and is this normal behavior?

Daan
  • 1,417
  • 5
  • 25
  • 40

2 Answers2

3

As M. Harris already said in 2003 and the docs for the logical operators (e.g. Or) state explicitly, VBScript does not short-circuit the evaluation of conditionals. You must use nested Ifs or a slightly fancy Select Case

Community
  • 1
  • 1
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96
  • Ah thanks! I couldn't find the answer but now I know that it's called short-circuiting. – Daan May 04 '14 at 18:08
0

You can use inline nested IF's to achieve short-circuiting in VBScript. For example, you could rewrite your statement like this:

If oFS.FileExists(sFileLoc) Then If sNewText = oFS.OpenTextFile(sFileLoc).ReadAll Then

But your Then condition must be specified on the same line as this statement. So if you need to perform multiple operations as a result of this condition, you must separate the statements with a colon (:), which is the single-line statement separator in VBScript.

If oFS.FileExists(sFileLoc) Then If sNewText = oFS.OpenTextFile(sFileLoc).ReadAll Then x = 1 : y = 2

You could also just move your logic into a Sub or Function and make a call instead:

If oFS.FileExists(sFileLoc) Then If sNewText = oFS.OpenTextFile(sFileLoc).ReadAll Then DoStuff

Note, too, that if you need to specify an Else clause, it must be specified on this line as well.

If oFS.FileExists(sFileLoc) Then If sNewText = oFS.OpenTextFile(sFileLoc).ReadAll Then x = 1 Else x = 2
Bond
  • 16,071
  • 6
  • 30
  • 53
  • In how far is it required to put the nested if's into one line? And where is the End if? What the IF? – TheBlastOne May 05 '14 at 09:57
  • @TheBlastOne Lol. `End If` is not used in the single-line `If` construct. Only `If`, `Then`, and an optional `Else` are used. But you can still nest multiple `If`s, as shown above. – Bond May 05 '14 at 12:15