How can we implement continue and break functionality in SmartPy ?
SmartPy currently has no equivalent to Python’s continue
and break
to skip/abort loop iterations, as it’s not straight-forward to compile it to Michelson. Your best bet is to use a boolean variable that stops the iteration.
1 Like
Thank you . How you explain it with an example. How do we stop it using boolean. You mean using if else ?
Here is a made-up example that emulates break
. As soon as the boolean variable brk
becomes True
, the loop body is skipped at each iteration.
brk = False
for i in sp.range(0,10):
if not brk:
self.data.s += i # do something...
if i == 5:
brk = True # this is like 'break'
The actual loop doesn’t stop, but it shouldn’t be an issue unless the range is huge.
For continue
you probably don’t need a variable, but can just restructure your code with an if
statement. Happy to comment on a concrete example if you encounter any difficulties.
1 Like