WebAssembly WAT: Functions and Locals
WAT functions and locals are the parts that give a function inputs, a result, and working space. A local is one extra slot a function can use while it runs.
The whole square module
This module squares one whole number.
(module
(func (export "square") (param i32) (result i32)
(local i32)
local.get 0
local.set 1
local.get 1
local.get 1
i32.mul))Save the input
These lines copy the input into slot 1.
local.get 0
local.set 1Multiply the slot by itself
These lines push slot 1 twice and multiply.
local.get 1
local.get 1
i32.mulSquare 6 from a page
This call runs square with 6.
console.log(instance.exports.square(6));Example
const B64 = "AGFzbQEAAAABBgFgAX8BfwMCAQAHCgEGc3F1YXJlAAAKDwENAQF/IAAhASABIAFsCw==";
(async () => {
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes, {});
console.log('6 squared =', instance.exports.square(6));
console.log('7 squared =', instance.exports.square(7));
})();Key points
- Param: one input value a function takes in.
- Result: one output value a function gives back.
- Local: one extra slot a function can use while it runs.
- Use (local i32) to add one whole-number slot to a function.
- Use local.set 1 to store a value in slot 1.
- Use local.get 1 to read the value back from slot 1.
- Use i32.mul to multiply two whole numbers.
In this example, the first line holds the module bytes as text. The next line turns that text into bytes. Then the code builds the module and waits for it. Then it calls square with 6. Then it calls square with 7. The two lines print 36 and 49. A local holds the input so the function can use it twice.
Note
In square, slot 0 is the input, so the local is slot 1.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
In square, what does local.set 1 do?