loop

loop 語句建立一個標籤,稍後可以使用 br 指令跳轉到該標籤。loop 指令本身不會迴圈;您需要跳轉到它才能實際建立迴圈。

loop 語句與 block 語句是相反的,因為跳轉到 loop 會跳到迴圈的開頭,而跳轉到 block 會跳到塊的末尾,也就是跳出該塊。

試一試

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

  (func
    ;; create a local variable and initialize it to 0
    (local $i i32)

    (loop $my_loop

      ;; add one to $i
      local.get $i
      i32.const 1
      i32.add
      local.set $i

      ;; log the current value of $i
      local.get $i
      call $log

      ;; if $i is less than 10 branch to loop
      local.get $i
      i32.const 10
      i32.lt_s
      br_if $my_loop

    )
  )

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

語法

wat
;; label the loop so that it can be branched to
(loop $my_loop

  ;; branch to the loop.
  ;; most of the time you'll want to put this in an if statement and only branch on condition,
  ;; otherwise you have an infinite loop.
  br $my_loop

)
指令 二進位制操作碼
loop 0x03