Tables and call_indirect in WebAssembly
Function pointers: a table of funcrefs picked by runtime index.
(module
;; A table of function references, picked at run time by index:
;; this is how function pointers and vtables compile to wasm.
(type $unop (func (param i32) (result i32)))
(table 2 funcref)
(elem (i32.const 0) $double $negate)
(func $double (param $n i32) (result i32)
(i32.mul (local.get $n) (i32.const 2)))
(func $negate (param $n i32) (result i32)
(i32.sub (i32.const 0) (local.get $n)))
(func (export "apply") (param $which i32) (param $n i32) (result i32)
(call_indirect (type $unop) (local.get $n) (local.get $which))))
How it works
(table 2 funcref)and(elem ...)fill two slots with functions.(type $unop ...)declares the signature the call will check.call_indirecttakes the argument, then the index — wrong types trap.
Keywords and builtins used here
call_indirectelemexportfuncfuncrefi32moduleparamresulttabletype
The run, in numbers
- Lines
- 14
- Characters to type
- 534
- Tokens
- 120
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 120 seconds.
Step 3 of 3 in Calls, step 15 of 28 in Language basics.