typestar

Multiple results in WebAssembly

A function may leave several values; the caller uses them in order.

(module
  ;; A function may leave several results on the stack; the caller
  ;; receives them in order.
  (func $divmod (export "divmod") (param $n i32) (param $d i32)
        (result i32 i32)
    (i32.div_s (local.get $n) (local.get $d))
    (i32.rem_s (local.get $n) (local.get $d)))

  ;; The two results feed the next instruction like any operands.
  (func (export "digit_sum_2") (param $n i32) (result i32)
    (call $divmod (local.get $n) (i32.const 10))
    i32.add))

How it works

  1. (result i32 i32) types two returns — here quotient and remainder.
  2. The body pushes both; nothing more is needed.
  3. The caller's i32.add consumes the pair straight off the stack.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
440
Tokens
84
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 3 of 3 in Wider types, step 25 of 28 in Language basics.

← Previous Next →