Guides/WebAssembly

From J Wiki
Jump to navigation Jump to search

WebAssembly is a binary instruction format for a stack-based virtual machine, designed to enable high-performance applications on the web.

Emscripten is an open-source compiler that converts C/C++ code into WebAssembly.

The J Playground is an online J IDE that includes a version of J compiled to WebAssembly.

The source code for the playground is at github:jsoftware/j-playground

If you want to run J via wasm in your own application, you can use the build tools there, or just copy the following three files from the playground:

To use these files, create an HTML page that loads emj.js.

The code in emj.js loads the other two files and defines a global variable called Module that wraps the J interpreter.

The wrapper expects you to define a top-level function called jdo1 by calling Module.cwrap to expose the internal em_jdo function.

Once you've done this, you can pass jdo1 a string containing a line of J code, and it will return a string with the results. (The output is also sent to the javascript console).

Here is an example html file that demonstrates how to use it:

   
<!doctype html>
<html>
  <head>
    <title>j wasm demo</title>
    <script src="emj.js"></script>
    <script>
      var jdo1 = Module.cwrap('em_jdo','string',['string'])
    </script>
    <style>
      textarea, input { font-family: consolas, monospace; width: 640px }
    </style>
  </head>
  <body>
    <h1>j wasm demo</h1>
    <textarea id="jout" rows="25" readonly></textarea>
    <br><input id="jsrc" value="" placeholder="i.10  NB. type J code here" autofocus/>
    <script>
      let jsrc = document.getElementById("jsrc")
      let jout = document.getElementById("jout")
      jsrc.onkeypress = function(e){
        var key = e.code || e.key;
        if (key == 'Enter'){
          jout.value += '\n   '+jsrc.value
          jout.value += '\n' + jdo1(jsrc.value)
          jsrc.value =''
        }}
    </script>
  </body>
</html>


To call JavaScript from J, use 2!:0 (the Execute Host Command Foreign)

For example: (2!:0) 'alert("hello")'