views:

56

answers:

4

A colleague and I were trying to figure out a way of doing the equivalent of a "continue" statement within a VBScript "For/Next" loop.

Everywhere we looked we found people had no way to do this in VBScript without having nasty nestings, which is not an option for us since it is a quite big loop.

We came out with this idea. Would it work just as a "continue(to next iteration)"? Does anyone have any better workaround or improvement suggestion?

For i=1 to N
  For workaroundloop = 1 to 1
    [Code]
    If Condition1 Then
      Exit For
    End If

    [MoreCode]
    If Condition2 Then
      Exit For
    End If

    [MoreCode]
    If Condition2 Then
      Exit For
    End If

    [...]

  Next
Next

Thanks for your comments

+1  A: 

One option would be to put all the code in the loop inside a Sub and then just return from that Sub when you want to "continue".

Not perfect, but I think it would be less confusing that the extra loop.

Edit: Or I suppose if you're brave enough you could use a Goto to jump to the beginning of the loop in some way (making sure that the counter gets updated correctly), I think VBScript supports that, but your reputation might suffer if someone discovers that you're using Goto in your code :)

ho1
If any, I would use the GoTo to go to the end of the loop so the counter goes +1, but I've come to understand that there is no GoTo support on VBScript :P
EKI
A: 

Implement the iteration as a recursive function.

Function Iterate( i , N )
  If i == N Then
      Exit Function
  End If
  [Code]
  If Condition1 Then
     Call Iterate( i+1, N );
     Exit Function
  End If

  [Code]
  If Condition2 Then
     Call Iterate( i+1, N );
     Exit Function
  End If
  Call Iterate( i+1, N );
End Function

Start with a call to Iterate( 1, N )

Captain Giraffe
Though you have to be a little careful, if N is big enough, this could lead to a Stackoverflow (as mentioned in the spec here: http://msdn.microsoft.com/en-us/library/x7hbf8fa%28VS.85%29.aspx).
ho1
+1  A: 

Your suggestion would work, but using a Do loop might be a little more readable.

This is actually an idiom in C - instead of using a goto, you can have a do { } while (0) loop with a break statement if you want to bail out of the construct early.

Dim i

For i = 0 To 10
    Do
        If i = 4 Then Exit Do
        WScript.Echo i
    Loop While False
Next
Tmdean
A: 

I use to use the Do, Loop a lot but I have started using a Sub or a Function that I could exit out of instead. It just seemed cleaner to me. If any variables you need are not global you will need to pass them to the Sub also.

For i=1 to N
 DoWork i
Next

Sub DoWork(i)
    [Code]
    If Condition1 Then
      Exit Sub
    End If

    [MoreCode]
    If Condition2 Then
      Exit Sub
    End If

    [MoreCode]
    If Condition2 Then
      Exit Sub
    End If

    [...]
End Sub
wsware