Breaking from a for/while/etc. and the role of ^

Hi,

New to the forum and relatively new to SC (started looking into it few months ago).
I was looking into how to “break” from a loop (for/while/etc.) and found out that there is the Function instance method “block” that does that (it seems something SC inherited form Smalltalk).
But, I also started poking around and found out that using ^ works as well.
I’m aware that ^ is only used to return within Class/Instance methods, but that seems to be doing something here as well.
It is breaking from the for but, is not returning anything though, as showed in this code

(
for (1, 10) { |x|
	if (x == 3) {^3};
	x.postln;
}
)

interestingly enough, this other code shows something else too

(
for (1, 10) { |x|
	if (x == 3) {^3};
	x.postln;
};
"done".postln;
)

the for loop stops, nothing is returned and “done”.postln is not executed.

Can anybody help me understanding what’s happening under the hood?

Cheers,
Mario

I think it breaks from the whole block of code, meaning everything in the parenthesis.
Basically, ^ does not work outside of Classes, don’t use it. I imagine its like a virtual machine with a return register and the pointer to the next block of code gets lost.

If the predicate is fixed, you can use reject to remove the elements before the iteration.

(1..10).reject(_ == 3).do(_.postln)

If not, you must use an if inside the loop for continue, and a while loop with a var for break.

1 Like

Nice! That makes sense, thanks @jordan