Globals
Globals are global variables
. These variables can be accessed from both host code and within WebAssembly instances. Globals can be defined as mutable or immutable. This is done through the mutable
property, with the possible values true
or false
. Globals can be both imported into a module, and exported from one.
Types
Global values are WebAssembly.ValueTypes, which can be of the following types:
abbreviation | explanation |
---|---|
anyfunc | Reference to a function |
externref | Reference to entity in host environment |
f32 | 32 bit float |
f64 | 64 bit float |
i32 | 32 bit integer |
i64 | 64 bit integer |
v128 | 128 bit vector |
Examples:
Creating a global will look something like this :
const aGlobal = new WebAssembly.Global({ value: "i32", mutable: true }, aValue);
let engine = Engine::default();
let mut store = Store::new(&engine, ());
let module = Module::from_file(&engine, "module.wasm")?;
let global_type = GlobalType::new(ValType::I32, Mutability::Var);
let a_global = Global::new(&mut store, global_type, a_value.into())?;
Accessing an exported global will look something like this:
WebAssembly.instantiateStreaming(
fetch("moduleOrComponent.wasm"),
importsObject
).then(({ obj }) => {
const aGlobalRef = obj.exports.getGlobal(); // getting a reference to an exported modal
});
let engine = Engine::default();
let mut store = Store::new(&engine, ());
let module = Module::from_file(&engine, "module.wasm")?;
let instance = Instance::new(&mut store, &module, &[])?;
let a_global_ref = instance.get_global(&mut store, "a_global").unwrap();
Additional reading
Read more about about globals and how to work with them in Mozilla’s WebAssembly documentation, here.