🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly Tables: Indirect Calls

A table is a list of function references held by a module. An indirect call picks a function from the table by its index and calls it.

A table with two functions

The table holds add at index 0 and multiply at index 1. Apply calls one of them by index.

(module
  (type $binop (func (param i32 i32) (result i32)))
  (table 2 funcref)
  (elem (i32.const 0) $add $multiply)
  (func $add (param i32 i32) (result i32)
    local.get 0
    local.get 1
    i32.add)
  (func $multiply (param i32 i32) (result i32)
    local.get 0
    local.get 1
    i32.mul)
  (func (export "apply") (param i32 i32 i32) (result i32)
    local.get 1
    local.get 2
    local.get 0
    call_indirect (type $binop)))

Call add through the table

Index 0 picks add. So apply with 0, 3, and 4 gives 7.

console.log(instance.exports.apply(0, 3, 4));

Call multiply through the table

Index 1 picks multiply. So apply with 1, 3, and 4 gives 12.

console.log(instance.exports.apply(1, 3, 4));

Example

(async () => {
  const B64 = "AGFzbQEAAAABDgJgAn9/AX9gA39/fwF/AwQDAAABBAQBcAACBwkBBWFwcGx5AAIJCAEAQQALAgABCh0DBwAgACABagsHACAAIAFsCwsAIAEgAiAAEQAACw==";
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes);
  console.log(instance.exports.apply(0, 3, 4));
  console.log(instance.exports.apply(1, 3, 4));
})();

Key points

  • A table is a list of function references.
  • Each entry in a table holds one function.
  • Call_indirect calls the function at a given index.
  • The index is the last value on the stack.
  • The function type must match the call type.

In this example, the bytes are decoded and started into an instance. Then apply is called with index 0, which picks add, so 3 and 4 give 7. Then apply is called with index 1, which picks multiply, so 3 and 4 give 12.

Note

A wrong type fails instantiation with a LinkError.

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

How does call_indirect choose which function to run?