Changes how examples are tested, and fixes ExitError bug (#468)
Before, we tested the examples/ directory using "ExampleXX", but this is not ideal because it literally embeds the call to `main` into example godoc output. This stops doing that for a different infrastructure. This also makes sure there's a godoc example for both the main package and wasi, so that people looking at https://pkg.go.dev see something and also a link to our real examples directory. Signed-off-by: Adrian Cole <adrian@tetrate.io>
This commit is contained in:
43
example_test.go
Normal file
43
example_test.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package wazero
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"log"
|
||||
)
|
||||
|
||||
// This is an example of how to use WebAssembly via adding two numbers.
|
||||
//
|
||||
// See https://github.com/tetratelabs/wazero/tree/main/examples for more examples.
|
||||
func Example() {
|
||||
// Create a new WebAssembly Runtime.
|
||||
r := NewRuntime()
|
||||
|
||||
// Add a module to the runtime named "wasm/math" which exports one function "add", implemented in WebAssembly.
|
||||
mod, err := r.InstantiateModuleFromCode([]byte(`(module $wasm/math
|
||||
(func $add (param i32 i32) (result i32)
|
||||
local.get 0
|
||||
local.get 1
|
||||
i32.add
|
||||
)
|
||||
(export "add" (func $add))
|
||||
)`))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer mod.Close()
|
||||
|
||||
// Get a function that can be reused until its module is closed:
|
||||
add := mod.ExportedFunction("add")
|
||||
|
||||
x, y := uint64(1), uint64(2)
|
||||
results, err := add.Call(nil, x, y)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Printf("%s: %d + %d = %d\n", mod.Name(), x, y, results[0])
|
||||
|
||||
// Output:
|
||||
// wasm/math: 1 + 2 = 3
|
||||
}
|
||||
Reference in New Issue
Block a user