Last active
September 21, 2017 18:39
-
-
Save binji/09e61f11f7b9307bcbcc120b95cf4162 to your computer and use it in GitHub Desktop.
Simple WebAssembly Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
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
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!