Exit
From REALbasicWiki
Exit is a control statement that ends execution of a loop or method. Exit can take certain keyword parameters that allow more precise control over what is exited.
Contents |
[edit] Exit
Calling Exit with no parameters causes execution to jump out of the innermost loop block containing it to the next statement. Here is a simple example.
Function IndexOf(theList as Object, theObject as Object)
dim theIndex as Integer = -1
for i as Integer = 0 to UBound(theList)
if theList(i) is theObject then
theIndex = i
exit
end if
next
return theIndex
End Function
If a match is found, exit causes execution to jump to the next statement following the loop, return theIndex.
[edit] Exit [For|Do|While]
You can pass one of the keywords For, Do, or While as a parameter. This tells Exit to jump out of the innermost For|Do|While block containing it. In the example that follows, the statement exit do jumps out of the do loop containing it.
do
while true
exit do
wend
loop
[edit] Exit For loopVariable
In the presence of nested for loops, you can pass an additional parameter, the loop variable, to Exit For to indicate which For-Next loop you intend to exit. Here is the canonical example.
for x as Integer = 0 to lastX
for y as Integer = 0 to lastY
if someCondition then
exit for x
end if
next
next
This also works for For Each loops, and the loop variable need not be a numeric datatype. I contrive an example.
dim theList() as FolderItem
theList.Append DesktopFolder
for each foo as FolderItem in theList
for i as Integer = 0 to 10
exit for foo
next
next
[edit] Exit [Sub|Function]
Passing one of the keywords Sub or Function means that control will jump to the end of the method. The compiler requires that you call Exit Sub only within a subroutine, and Exit Function within a function. This is almost the same behavior as Return, except that one cannot return a value. It is unclear why this option is even available.
[edit] Exit outside a loop
Beware that if Exit is not contained within a For-Next, While-Wend, or Do-Loop looping block, its execution will cause control to jump to the end of the method, similar to calling Exit Sub or Exit Function. Here is an example.
Sub Example() if true then exit end if MsgBox "Msgbox" End Sub
Here, the MsgBox statement is skipped because Exit causes control to jump to the end of the method. If the method is a function, then the default value will be returned.
