typestar

Globals in WebAssembly

Module-level state; only (mut ...) globals accept writes.

(module
  ;; Globals live outside any function; only (mut ...) ones may be
  ;; written after instantiation.
  (global $visits (mut i32) (i32.const 0))
  (global $capacity i32 (i32.const 18))

  (func (export "check_in") (result i32)
    (global.set $visits
      (i32.add (global.get $visits) (i32.const 1)))
    (global.get $visits))

  (func (export "beds_left") (result i32)
    (i32.sub (global.get $capacity) (global.get $visits))))

How it works

  1. (global $visits (mut i32) ...) is writable; $capacity is not.
  2. global.set after a global.get and add makes an increment.
  3. Immutable globals are named constants the engine can fold.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
408
Tokens
82
Three-star pace
65 tpm

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

Type this snippet

Step 1 of 3 in Globals & startup, step 20 of 28 in Language basics.

← Previous Next →

Globals in other languages