singularity

WAT variables

Global vars and type conversion

WAT has four global and local variable types:

Local variables

Unpacking S-expressions

Indexed variables

Converting between types

if/else conditional Logic

;; This code is for demonstration and not part of a larger app
(if (local.get $bool_i32)
  (then
    ;; do something if $bool_i32 is not 0
    ;; nop is a 'no operation' opcode.  
    nop ;; I use it to stand in for code that would actually do something.
  )
  (else
    ;; do something if $bool_i32 is 0
    nop
  )
)

(if
  (i32.and
    (i32.gt_s (local.get $x) (local.get $y) ) ;; signed greater than
    (i32.lt_s  (local.get $y) (i32.const 6) ) ;; signed less than
  )
  (then
    ;; x is greater than y and y is less than 6
    nop
  )
)

Loops and blocks

If you want your code to jump backward, you must put your code inside a loop. If you want your code to jump forward, you must put it inside a block.

The Block Statement

The loop expression

using block and loop together

[ex 05/index]

branching with br_tables

Another way to use the block expression in WAT is in conjunction with a br_table expression, which allows you to implement a kind of switch statement. It’s meant to provide the kind of jump table performance you get with a switch statement when there are a large number of branches. The br_table expression takes a list of blocks and an index into that list of blocks. It then breaks out of whichever block your index points to. The awkward thing about using a branch table is that the code can only break out of a block it’s inside. That means you must declare all of your blocks ahead of time.

;; This code is for demonstration and not part of a larger app
1 (block $block_0
(block $block_1
(block $block_2
(block $block_3
(block $block_4
(block $block_5
2 (br_table $block_0 $block_1 $block_2 $block_3 $block_4 $block_5
  (local.get $val)
)
3 ) ;; block 5
i32.const 55
return

)   ;; block 4
i32.const 44
return

)    ;; block 3
i32.const 33
return

)    ;; block 2
i32.const 22
return

)    ;; block 1
i32.const 11
return

)   ;; block 0
i32.const 0
return

functions and tables

[ex 06/index]