The global definition declares a new global variable.
(module
(import "console" "log" (func $log (param i32)))
;; Import a global variable from js
(import "env" "from_js" (global $from_js i32))
;; Create a global variable
(global $from_wasm (mut i32) (i32.const 10))
(func $main
;; Set $from_wasm to a different value
i32.const 20
global.set $from_wasm
;; Load both global variables onto the stack
global.get $from_js
global.get $from_wasm
i32.add ;; Add up both globals
call $log ;; Log the result
)
(start $main)
)const url = "{%wasm-url%}";
const from_js = new WebAssembly.Global({ value: "i32", mutable: false }, 5);
await WebAssembly.instantiateStreaming(fetch(url), {
console,
env: { from_js },
});global identifier type initial_value
globalThe global definition type. Must always be included first.
identifier OptionalAn identifying name for the global. This must begin with a $ symbol, for example $my_global.
typeThe type of global to create. This consists of a data_type, optionally preceded by the mut keyword:
mut OptionalThe mut flag. If included, the global is mutable — it can be set to a different value after initialization via the global.set instruction.
data_typeThe data type of the global. This can be one of the following:
initial_valueThe initializer for the new global. Its value can be:
i32.const 0.global.get of another global.The initial_value type must be the same as the declared type.
The WebAssembly global definition enables globally-scoped variables to be defined inside a Wasm module. Global variables can be:
Retrieved via global.get and used from anywhere inside the module.
Mutated via global.set, provided the mut flag was included when the global was declared. Attempting to mutate a non-mutable variable results in a validation error.
Exported to pass them into JavaScript. For example:
(global $my_global (mut i32) (i32.const 0))
(export "my_global" (global $my_global))Note: If a global contains a v128 (SIMD) or exception (exnref) type, you can export it, but attempting to read the global's value via JavaScript will result in a TypeError.
It is also possible to create a Wasm global from within the JavaScript host using the WebAssembly.Global() constructor then importing it into the module.
For example:
const myGlobal = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
const { instance } = await WebAssembly.instantiateStreaming(
fetch("example.com/module"),
{
env: { myGlobal },
},
);It is possible to share globals declared inside Wasm modules, or inside the JavaScript host, between multiple modules.
For example, the state of the global created below is shared between two different modules:
const shared = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
const modA = await instantiate(bytesA, { env: { shared } });
const modB = await instantiate(bytesB, { env: { shared } });global.getglobal.setWebAssembly.Global JavaScript interface