Discuss Scratch
- Discussion Forums
- » Help with Scripts
- » Break out of loop
- 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:
How do you do this with Scratch?
Thanks!
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.
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
- 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
- helloworldbyeworld
- Scratcher
1000+ posts
Break out of loop
Thank you for your help!
Helloworldbyeworld | 1200+ posts
Have a great day
- Discussion Forums
- » Help with Scripts
- » Break out of loop