use mlua::Lua; use std::error::Error; #[test] fn wasmer_examples_exports_global() -> Result<(), Box> { let lua = Lua::new(); mlua_wasmer::preload(&lua)?; let script = r#" -- Let's declare the Wasm module with the text representation. local module_wat = [[ (module (global $one (export "one") f32 (f32.const 1)) (global $some (export "some") (mut f32) (f32.const 0)) (func (export "get_one") (result f32) (global.get $one)) (func (export "get_some") (result f32) (global.get $some)) (func (export "set_some") (param f32) (global.set $some (local.get 0)))) ]] -- Create a Store. local wasmer = require('wasmer') local store = wasmer.Store:default() -- Let's compile the Wasm module. print('Compiling module...') local module = wasmer.Module:new(store, module_wat) -- Create an empty import object. local import_object = wasmer.Imports:new() -- Let's instantiate the Wasm module. print('Instantiating module...') local instance = wasmer.Instance:new(store, module, import_object) -- Here we go. The Wasm module exports some globals. Let's get them. local one = instance.exports:get_global('one') local some = instance.exports:get_global('some') -- Lets get the globals types. The results are GlobalType's. print('Getting globals types information...') local one_type = one:ty(store) local some_type = some:ty(store) print(string.format('one type: %s %d', tostring(one_type.mutability), one_type.ty)) -- Getting the values of globals can be done in two ways: -- 1. Through an exported function, -- 2. Using the Global API directly. -- -- We will use an exported function for the `one` global -- and the Global API for `some`. print("Getting global values...") local get_one = instance.exports:get_function('get_one') local one_value = get_one:call(store) local some_value = some:get(store) print(string.format('one value: %s', tostring(one_value))) assert(one_value == 1.0) print(string.format('some value: %s', tostring(some_value))) assert(some_value:f32() == 0.0) -- Trying to set the value of a immutable global (`const`) -- will result in a `RuntimeError`. -- TODO "#; lua.load(script).exec()?; Ok(()) }