Discuss Scratch

helloworldbyeworld
Scratcher
1000+ posts

Break out of loop

Hi,

In most text based programming languages, there is a command to break out of a loop. What I mean is this:

repeat (foo)
if <something> then
Break out of loop // exit the loop and continue with the script
end
end

How do you do this with Scratch?

Thanks!

Helloworldbyeworld | 1200+ posts
Have a great day
TheAnomalousPseudo
Scratcher
1000+ posts

Break out of loop

Rather than “repeat ()” use “repeat until” and make an index variable.

Let's say you want a loop to repeat 20 times or until the space key is pressed.

set [foo v] to (0) //I use foo as index
set [stop v] to (0)
repeat until <<(foo) > (19)> or <(stop) = (1)>>
...::#999999
change [foo v] by (1)
end
set [stop v] to (0)

forever
if <key [space v] pressed?> then
set [stop v] to (1)
end
end

Last edited by TheAnomalousPseudo (May 30, 2021 03:06:22)



We ought to be careful with that octopus that takes over the servers. He's well armed.
awesome-llama
Scratcher
1000+ posts

Break out of loop

Alternatively to what TheAnomalousPseudo answered above, you can also take the blocks which are supposed to be after the loop and nest them inside. Then you use the “stop this script” block to stop the loop from running again.

repeat (20)
if <something::grey> then
... // the scripts you wanted to put after the loop go here instead
stop [this script v] // prevents the loop from running again
end
end


rudrav
Scratcher
53 posts

Break out of loop

Use a variable to stop the loop!
Hope this helps YOU.

My profile: https://scratch.mit.edu/users/rudrav/
say [ A follow will be apprecited ] for (2) secs
j_a_n_t_i
Scratcher
500+ posts

Break out of loop

forever
if <... ::sensing> then
broadcast [... v]
stop [this script v]
end
end
when I receive [... v]
Your code... ::grey
Vadik1
Scratcher
500+ posts

Break out of loop

... //Your code before the loop
Breakable loop
... //Your code after the loop

define Breakable loop
repeat (foo)
if <something> then
stop [this script v]// exit the loop and continue with the script
end
end

I mostly make 3D projects. Here are some of them:

helloworldbyeworld
Scratcher
1000+ posts

Break out of loop

Thank you for your help!

Helloworldbyeworld | 1200+ posts
Have a great day

Powered by DjangoBB