typestar

Linear memory in WebAssembly

One flat run of bytes, addressed by arithmetic you write yourself.

(module
  ;; Linear memory is a flat run of bytes; store and load move i32s
  ;; at byte addresses the code computes itself.
  (memory (export "mem") 1)

  (func (export "stash") (param $slot i32) (param $value i32)
    (i32.store
      (i32.mul (local.get $slot) (i32.const 4))
      (local.get $value)))

  (func (export "fetch") (param $slot i32) (result i32)
    (i32.load (i32.mul (local.get $slot) (i32.const 4)))))

How it works

  1. (memory (export "mem") 1) declares one 64 KiB page.
  2. i32.store takes an address and a value; slots are 4 bytes apart.
  3. i32.load reads the same address math back.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
391
Tokens
84
Three-star pace
65 tpm

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

Type this snippet

Step 1 of 4 in Memory, step 16 of 28 in Language basics.

← Previous Next →