Global Variables and Constants
Learn how to use global variables and constants in WebAsemmbly.
We'll cover the following...
The globals section is where we can import and export values in and out of WebAssembly modules. In a WebAssembly module, you can import either mutable or immutable values from JavaScript. Additionally, WebAssembly also supports wasmValue, an internal immutable value inside the WebAssembly module itself.
Let’s create a file called globals.wat and add the following contents to it:
(module(global $mutableValue (import "js" "mutableGlobal") (mut i32))(global $immutableValue (import "js" "immutableGlobal") i32)(global $wasmValue i32 (i32.const 10))(func (export "getWasmValue") (result i32)(global.get $wasmValue))(func (export "getMutableValue") (result i32)(global.get $mutableValue))(func (export "getImmutableValue") (result i32)(global.get $immutableValue))(func (export "setMutableValue") (param $v i32)(global.set $mutableValue(local.get $v))))
We created a module (module) and three global variables:
- $mutableValue: This value is imported from the- mutableGlobalvariable inside the- jsJavaScript module. We also define the global variable to be of the- mut- i32type.
- $immutableValue: This value is imported from the- immutableGlobalvariable inside the- jsJavaScript module. We also define the global variable to be of the- i32type.
- $wasmValue: This is a global constant. We define the- globalkeyword followed by the name of the global variable,- $wasmValue, then the type of- i32, and finally the actual value (- i32.const 10).
Note:
$wasmValueis immutable and cannot be exported to the external world.
Then, we have a set of functions that helps to get of and set the global variables. getWasmValue,  ...