(global...)
Create a global variable that be used throughout the module and even be used outside WASM in JavaScript.
If you are importing or exporting the global variable then you will need to use the WebAssembly.Global
object on the JavaScript side.
Syntax
(global $label type expression )
(global $label (mut type) expression )
(global $label (import...) type )
(global $label (export...) type expression)
Parameters
$label Optional
The label name of the global variable. Each global variable can be used either with the label or
using an index to it. The first global variable is given the index of 0, with the next index being
1, and so on.
type
The data type the variable uses.
expression Optional
Used to set the starting value of the global variable.
Use something like (i32.const 0)
depending on the data type of the global variable.
When exporting the expression is required.
mut Optional
Used to set if the global variable mutable (can be changed) or immutable (cannot be changes).
By default all global variables act like constants which cannot be changed.
(import...) Optional
Used to import the global variable from JavaScript.
(export...) Optional
Used to export the global variable to JavaScript.
Examples
Internal Constant
(global $piDiv180 f64 (f64.const 0.0174533))
(func $degreeToRadian (param $degree f64) (result f64)
global.get $piDiv180
local.get $degree
f64.mul
)
Internal Variable
(global $vectorX (mut f64) (f64.const 0))
(func $scaleVectorX (param $scaler f64)
global.get $vectorX
local.get $scaler
f64.mul
global.set $vectorX
)
Imported From Literal
(global $maxCount (import "import" "maxCount") f64)
const options = {
import: {
maxCount: 101
}
}
const promise = WebAssembly.instantiate(wasmData, options);
Imported From Literal
(global $upperLimit (import "import" "upperLimit") (mut i32))
const upperLimit = new WebAssembly.Global({ value: 'i32', mutable: true }, 404);
const options = {
import: {
upperLimit: upperLimit
}
}
const promise = WebAssembly.instantiate(wasmData, options);
Exported
(global $lowerLimit (export "lowerLimit") (mut i32) (f64.const 10))
const wasm = await WebAssembly.instantiateStreaming(fetch('app.wasm'));
const global = wasm.instance.exports.lowerLimit;