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 themutableGlobal
variable inside thejs
JavaScript module. We also define the global variable to be of themut
i32
type.$immutableValue
: This value is imported from theimmutableGlobal
variable inside thejs
JavaScript module. We also define the global variable to be of thei32
type.$wasmValue
: This is a global constant. We define theglobal
keyword followed by the name of the global variable,$wasmValue
, then the type ofi32
, and finally the actual value (i32.const 10
).
Note:
$wasmValue
is immutable and cannot be exported to the external world. ...