...

/

Global Variables and Constants

Global Variables and Constants

Learn how to use global variables and constants in WebAsemmbly.

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:

Press + to interact
(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 mutableGlobal variable inside the js JavaScript module. We also define the global variable to be of the mut i32 type.

  • $immutableValue: This value is imported from the immutableGlobal variable inside the js JavaScript module. We also define the global variable to be of the i32 type.

  • $wasmValue: This is a global constant. We define the global keyword followed by the name of the global variable, $wasmValue, then the type of i32, and finally the actual value (i32.const 10).

Note: $wasmValue is immutable and cannot be exported to the external world. ...