You can test your WebAssembly skills by using the WebAssembly Studio online tool.
First, JavaScript doesn’t support int64 yet, a signature with int64 in wasm can’t be exported to JS.
This means I will use only 32 support with JavaScript.
If you open this online tool will see this:
- this area will start the project;
- this area will store all project files;
- this area is for logs;
- this area will come with all tool (like Build, Run, Build & Run);
- in this area you can follow the result;
Using one Empty Wat Project will create all files to start using the WebAssembly project.
This project will come with these files: main.html, main.js, main.wat, and main.wasm.
All this file will create an output for a function add.
This function will return the result into id named container.
Anyway, I will show you how to make changes into this source code file to create another id and add a different function named sub.
Let’s see the source code for these files:
First, main.html will have two ids and this source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body { font-color: rgb(0,0,0) background-color: rgb(0, 0, 255); } </style> </head> <body> <span id="div_add"></span> <span id="div_sub"></span> <script src="./main.js"></script> </body> </html> |
The next file is main.js and will come with this source code:
1 2 3 4 5 6 7 | fetch('../out/main.wasm').then(response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes)).then(results => { instance = results.instance; document.getElementById("div_add").textContent = instance.exports.add(1,9); document.getElementById("div_sub").textContent = instance.exports.sub(9,1); }).catch(console.error); |
The result of this function: add and sub, will be put into div_add and div_sub.
The next source code is main.wat:
1 2 3 4 5 6 7 8 9 10 11 12 | (module (func $add (param $lhs i32) (param $rhs i32) (result i32) get_local $lhs get_local $rhs i32.add) (func $sub (param $lhs i32) (param $rhs i32) (result i32) get_local $lhs get_local $rhs i32.sub) (export "add" (func $add)) (export "sub" (func $sub)) ) |
The wat file type will solve the functions: add and sub.
One good documentation about these files can be found here.
The last source code is main.wasm:
1 2 3 4 5 6 7 8 9 10 | (module (type $t0 (func (param i32 i32) (result i32))) (func $add (export "add") (type $t0) (param $lhs i32) (param $rhs i32) (result i32) get_local $lhs get_local $rhs i32.add) (func $sub (export "sub") (type $t0) (param $lhs i32) (param $rhs i32) (result i32) get_local $lhs get_local $rhs i32.sub)) |
Use Build and Run buttons to run the example:
The result will show you: 10 8.
The WebAssembly is more complex that in this example, but can be used.
The syntax of WebAssembly’s tree is flat, mostly consisting of lists of instructions…