[Wish]: Allow Break Outside of a Loop, Such as In a Function
Posted: 18 Oct 2023, 21:00
Hi, for whatever reason, "break" cannot be put inside a function or a label, or really anywhere that isn't nested inside a loop, as per the documentation. You can't even do it if that function is inside a loop. I write Powershell scripts professionally, and use functions to nest my code, make it easier to write, and reduce total lines of code. I'll often have a function wrap something up or prepare something for later before I break a loop. As of now, functions cannot be used to break loops, because my script won't start.
Here is a basic example of what I want to do but can't. Start the loop with F7 and use ESC to trigger the function in the loop. I've commented out the "break", but ideally, "break" should replace the "exit". Exit does not have the functionality I need:
In powershell this is trivial to do:
Right now break isn't as "portable" as it should be, I should be able to break out of a loop no matter where I am, even if I'm calling "break" from a function. I can't even use GOTO for functionality similar to my Powershell example. I feel as though I should get an error at runtime when the script attempts to "break" something and it's not in a loop, instead of my script not launching at all.
Here is a basic example of what I want to do but can't. Start the loop with F7 and use ESC to trigger the function in the loop. I've commented out the "break", but ideally, "break" should replace the "exit". Exit does not have the functionality I need:
Code: Select all
; ESCAPE SEQUENCE---------------------------->
ToolTip "init"
ExitVar := 0
Esc:: {
global
;MsgBox "esc pressed"
ExitVar := 1
}
LoopExiter(ExitVar){
if(ExitVar = 1){
ExitVar := 0
MsgBox ExitVar " FROM FUNCTION"
Exit ;Comment this out and use break for example
;Break
}
}
; ESCAPE SEQUENCE---------------------------->
F7::{
global
Exitvar := 0
LoopNumber := 0
loop 10000000{
LoopExiter(ExitVar)
Tooltip LoopNumber += 1
;Sleep 1000
}
}
Code: Select all
function BreakFunction {
param (
$i
)
$a = 1
$b = 2
$Script:GetOut = "Out"
Write-host " I am doing other things inside the function before I use `"break`""
Write-host " I am passing a variable to the function, `$i:" $i
Write-host " I have defined two variables inside the function, `$a(1) and `$b(2), and can add them together here:" ($a+$b)
Write-host " I am making a variable available to the rest of the script from the function: `"`$GetOut`""
break
}
for ($i = 0; $i -lt 999999999; $i++) {
Write-Host "Loop iteration $i"
if ($i -ge 1000) {
Write-Host "This script will now break using the function `"BreakFunction`""
Write-Host ""
BreakFunction -i $i
}
}
Write-host ""
Write-host ""
Write-host "I have now broken out of the loop and functioning as normal"
Write-host "Variable from `"BreakFunction`": $GetOut"