Newer
Older
art_of_webassembly / ch03 / func_perform / func_perform.wat
@clewis clewis on 20 Mar 2024 1 KB initial commit
(module
    ;; external call to a JS function
    (import "js" "external_call" (func $external_call (result i32)))
    (global $i (mut i32) (i32.const 0))

    (func $internal_call (result i32) ;; returns an i32 to calling func
        global.get $i 
        i32.const 1
        i32.add

        global.set $i       ;; 1st 4 lines increment $i

        global.get $i       ;; return $i to calling func
    )

    ;; wasm_call will be called from JS
    (func (export "wasm_call")
        (loop $again
            call $internal_call     ;; returns $i on the stack
            i32.const 4_000_000     ;; push 4,000,000 onto stack
            i32.le_u                ;; is $i <= 4,000,000
            br_if $again            ;; if true, loop $again
        )
    )

    (func (export "js_call")
        (loop $again
            (call $external_call)   ;; calls the imported $external call
            i32.const 4_000_000     ;; push 4,000,000 onto stack
            i32.le_u                ;; is $i <= 4,000,000
            br_if $again            ;; if true, loop $again
        )
    )


) ;; end of module