call_indirect
Calls a function by its reference. You will need a table that contains a list of function references. These reference point to functions. You can select the function you want to call using an index to the function reference in the table. You will need to push any parameters that function needs onto the stack first, followed by the index of the function reference. Only then can the call_indirect instruction be used. Any results the function returns will be placed on the stack when the instruction is finished.

Syntax

call_indirect $table (type $functionType)

Parameters

$table Optional
The table the function reference is located. If not given then the default table is used. If used then this points to the (table...) object.
$functionType
Points to a predefinded function type. This is the prototype of the function, detailing the parameters and return data types. It is stating what the function looks like.

Stack In

i32 The index of the function reference in the table.

Stack Out

NONE

Example

;; Create function type
(type $functionType
  (func (param i32) (result i32))
)
  
;; Create table of function references
(table $testTable 4 funcref)

;; Create Add 1 function
(func $add1 (type $functionType)
    ;; Add one to parameter and return result
    local.get 0
    i32.const 1
    i32.add
)

;; Declare function can be a reference
(elem declare func $add1)

;; The function reference to $add1 was added to the default table
;; at index 0 at some other point

;; Test calling a function
(func $test (result i32)
    ;; Set function parameters
    i32.const 42

    ;; Set the index in the table where the function we
    ;; want to call is located
    i32.const 0

    ;; Call the function indirectly
    call_indirect $testTable (type $functionType)

    ;; The stack contains an i32 value of 43    
)