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
(local $high i32)reserves a slot; locals follow the params.local.setpops the stack into the slot;local.getpushes a copy.- The if swaps the two slots when the inputs arrive out of order.
Keywords and builtins used here
exportfunci32iflocalmoduleparamresultthen
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.
Step 1 of 3 in Locals & the stack, step 7 of 28 in Language basics.