loop and br in WebAssembly
On a loop, br jumps to the top: that is the whole while story.
(module
;; A loop label points at the top, so br means "go around again".
;; The surrounding block gives br_if somewhere to exit to.
(func (export "sum_to") (param $n i32) (result i32)
(local $i i32)
(local $acc i32)
(block $done
(loop $top
(br_if $done (i32.gt_s (local.get $i) (local.get $n)))
(local.set $acc (i32.add (local.get $acc) (local.get $i)))
(local.set $i (i32.add (local.get $i) (i32.const 1)))
(br $top)))
(local.get $acc)))
How it works
(loop $top ...)labels its own start;(br $top)goes around.- The enclosing
(block $done ...)givesbr_ifan exit. - The accumulator and counter are plain locals moved by set and add.
Keywords and builtins used here
blockbrbr_ifexportfunci32localloopmoduleparamresult
The run, in numbers
- Lines
- 13
- Characters to type
- 439
- Tokens
- 94
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 94 seconds.
Step 3 of 3 in Control flow, step 12 of 28 in Language basics.