🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly WAT: Control Flow

WAT control flow is the set of steps that choose a path or repeat steps. A loop runs its steps again until a test says stop.

The whole countdown module

This module counts down to zero and counts the steps.

(module
  (func (export "countdown") (param i32) (result i32)
    (local i32)
    (block $done
      (loop $again
        local.get 0
        i32.eqz
        br_if $done
        local.get 0
        i32.const 1
        i32.sub
        local.set 0
        local.get 1
        i32.const 1
        i32.add
        local.set 1
        br $again))
    local.get 1))

Stop at zero

These lines leave the block when the count hits zero.

local.get 0
i32.eqz
br_if $done

One step down

These lines take 1 from the count and add 1 to the steps.

local.get 0
i32.const 1
i32.sub
local.set 0
local.get 1
i32.const 1
i32.add
local.set 1

Repeat

This line jumps back to the top of the loop.

br $again

A small if

This test gives back 1 for zero and 0 for the rest.

local.get 0
i32.eqz
if (result i32)
  i32.const 1
else
  i32.const 0
end

Count down from 5

This call runs countdown with 5.

console.log(instance.exports.countdown(5));

Example

const B64 = "AGFzbQEAAAABBgFgAX8BfwMCAQAHDQEJY291bnRkb3duAAAKIwEhAQF/AkADQCAARQ0BIABBAWshACABQQFqIQEMAAsLIAEL";
(async () => {
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes, {});
  console.log('countdown(5) =', instance.exports.countdown(5));
  console.log('countdown(3) =', instance.exports.countdown(3));
})();

Key points

  • If: one step that runs its branch only when its test is true.
  • Block: one group of steps that a jump can leave early.
  • Loop: one group of steps that a jump can run again.
  • Br: one jump that leaves a block or restarts a loop.
  • Br_if: one jump that runs only when its test is true.
  • Use i32.eqz to test whether a value is zero.
  • Use i32.sub to take one whole number away from another.

In this example, the first line holds the module bytes as text. The next line turns that text into bytes. Then the code builds the module and waits for it. Then it calls countdown with 5. Then it calls countdown with 3. The two lines print 5 and 3. The loop repeats the same small steps until the count reaches zero.

Note

A loop needs a test that can stop it, or it runs forever.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What stops the countdown loop?