Skip to content

Instantly share code, notes, and snippets.

@binji
Last active September 21, 2017 18:39
Show Gist options
  • Save binji/09e61f11f7b9307bcbcc120b95cf4162 to your computer and use it in GitHub Desktop.
Save binji/09e61f11f7b9307bcbcc120b95cf4162 to your computer and use it in GitHub Desktop.
Simple WebAssembly Example
;; Convert this to add.wasm by running:
;;
;; wat2wasm add.wat -o add.wasm
;;
(module
(func (export "add") (param i32 i32) (result i32)
get_local 0
get_local 1
i32.add))
<!DOCTYPE html>
<body>
<input type="text" id="lhs" value="10">
+
<input type="text" id="rhs" value="20">
<button id="add">=</button>
<span id="result"></span>
<script src="example.js"></script>
</body>
let $ = x => document.querySelector(x);
let lhsEl = $('#lhs');
let rhsEl = $('#rhs');
let addEl = $('#add');
let resultEl = $('#result');
// Fetch add.wasm...
let addFuncPromise = fetch('add.wasm').then(
// Convert the response to an array buffer...
response => response.arrayBuffer()
).then(
// Use that array buffer to create a new instance...
buffer => WebAssembly.instantiate(buffer)
).then(
// And extract the exported "add" function from that instance.
({instance}) => instance.exports.add
);
// When the button is clicked...
addEl.addEventListener('click', () => {
// Wait for the addFuncPromise to resolve, then...
addFuncPromise.then((addFunc) => {
// Call the "add" function with the two inputs.
// The inputs will be automatically coerced from strings to int32 values,
// and the result of the function will be coerced from int32 to a string.
resultEl.textContent = addFunc(lhsEl.value, rhsEl.value);
});
});
@blakemcbride
Copy link

That's a big step in the right direction, but add.wat needs to be C code. That's what, I think, was intended, and the way most would want to use it. Thanks!

@binji
Copy link
Author

binji commented Sep 21, 2017

True, but once you do that you'll end up with something a lot more like the example on webassembly.org which is not going to be as lean.

Some other projects are aiming to generate WebAssembly using a typescript-like language, maybe that would be useful for you: https://github.com/AssemblyScript/assemblyscript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment