if...else

if 語句會在棧頂元素為 true(非零)時執行一條語句。如果條件為 false(0),則可以執行另一條語句。

試一試

(module
  ;; import the browser console object, you'll need to pass this in from JavaScript
  (import "console" "log" (func $log (param i32)))

  (func
    i32.const 0 ;; change to positive number (true) if you want to run the if block
    (if
      (then
        i32.const 1
        call $log ;; should log '1'
      )
      (else
        i32.const 0
        call $log ;; should log '0'
      )
    )
  )

  (start 1) ;; run the first function automatically
)
const url = "{%wasm-url%}";
await WebAssembly.instantiateStreaming(fetch(url), { console });

語法

wat
i32.const 0
(if
  (then
    ;; do something
  )
  (else
    ;; do something else
  )
)

要將返回值保留在棧中,請新增 result 語句。

wat
i32.const 0
(if (result i32)
  (then
    ;; do something
    (i32.const 1)
  )
  (else
    ;; do something else
    (i32.const 2)
  )
)
(drop)
指令 二進位制操作碼
if 0x04
else 0x05