typestar

Locals in WebAssembly

Declared up front, zero to start, moved with get and set.

(module
  ;; Locals are declared up front, zero-initialized, and read and
  ;; written with local.get and local.set.
  (func (export "swap_diff") (param $a i32) (param $b i32) (result i32)
    (local $high i32)
    (local $low i32)
    (local.set $high (local.get $a))
    (local.set $low (local.get $b))
    (if (i32.lt_s (local.get $high) (local.get $low))
      (then
        (local.set $high (local.get $b))
        (local.set $low (local.get $a))))
    (i32.sub (local.get $high) (local.get $low))))

How it works

  1. (local $high i32) reserves a slot; locals follow the params.
  2. local.set pops the stack into the slot; local.get pushes a copy.
  3. The if swaps the two slots when the inputs arrive out of order.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
452
Tokens
98
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 1 of 3 in Locals & the stack, step 7 of 28 in Language basics.

← Previous Next →