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
(global $visits (mut i32) ...)is writable;$capacityis not.global.setafter aglobal.getand add makes an increment.- Immutable globals are named constants the engine can fold.
Keywords and builtins used here
exportfuncglobali32modulemutresult
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.
Step 1 of 3 in Globals & startup, step 20 of 28 in Language basics.