Import/Export of Mutable Globals
Export a mutable global from Wasm
Section titled “Export a mutable global from Wasm”(module (global (export "counter") (mut i32) (i32.const 0)))From JS, read and write via .value:
const { instance } = await WebAssembly.instantiate(wasmBytes);console.log(instance.exports.counter.value); // 0instance.exports.counter.value = 5;console.log(instance.exports.counter.value); // 5Import a mutable global from JS
Section titled “Import a mutable global from JS”(module (import "env" "g" (global $g (mut i32))) (func (export "inc") (global.set $g (i32.add (global.get $g) (i32.const 1)))))Create a WebAssembly.Global on the JS side and pass it as an import:
const g = new WebAssembly.Global({ value: 'i32', mutable: true }, 0);const { instance } = await WebAssembly.instantiate(wasmBytes, { env: { g } });instance.exports.inc();console.log(g.value); // 1Instruction Reference
Section titled “Instruction Reference”- Local & Global Instructions —
global.get,global.set - Module Structure —
global,import,export