Jump to content

Flow-control structures: Difference between revisions

Added Wren
m (Fix Perl6 -> Raku links and comments)
(Added Wren)
Line 2,794:
Return CalculateAnotherValue()
End Function</lang>
 
=={{header|Wren}}==
Wren has just two control flow statements, '''break''' and '''return'''.
 
'''Break''' exits from the nearest enclosing for or while loop and transfers control to the next statement after that.
 
'''Return''' exits from a method or function and can be optionally followed by a value. Controls returns to the caller. Although undocumented, it can also be used to exit the script entirely from 'top level' code.
 
Whilst part of the standard library rather than the language itself, the '''Fiber.abort''' method can be used to exit the script when an error occurs. However, it is possible to catch the error using '''Fiber.try'''.
 
'''Fiber.suspend''' pauses the current fiber and stops the interpreter. Control returns to the host application, if there is one. However, execution of the script can be resumed later by storing a reference to the current fiber and then calling that.
 
The following code demonstrates each of the above apart from '''Fiber.suspend''' which simply exits a CLI script.
<lang ecmascript>var func = Fn.new { |n|
var i = 1
while (true) {
System.print(i)
if (i == n) break // exits while loop
i = i + 1
}
if (n < 3) return // exits function
System.print(n + 1)
}
 
var fiber = Fiber.new {
Fiber.abort("Demo error") // error occcurred, abort script
}
 
var a = [2, 3]
for (n in a) {
func.call(n)
if (n > 2) return // end script
var error = fiber.try() // catch any error
System.print("Caught error: " + error)
}</lang>
 
{{out}}
<pre>
1
2
Caught error: Demo error
1
2
3
4
</pre>
 
=={{header|zkl}}==
9,490

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.