Hello World with WebAssembly Text Format (WAT)

Simple WebAssembly Text Format (WAT) example for beginners showing a basic module exporting a function returning integer 42 without dependencies.

Brief Introduction

Hello World with WebAssembly Text Format (WAT) (wasm)
DESCRIPTION:
Simple and complete example of a WebAssembly module written in text format (WAT) that exports a function returning an integer value. This example is designed for absolute beginners and shows how to define a basic module without external dependencies.

ADDITIONAL NOTES:
This example is intentionally minimal to facilitate understanding of the WAT format and the basic structure of a WebAssembly module. It does not directly print 'Hello World' because WebAssembly has no direct access to the console; for textual output it is necessary to interface with the host (e.g., JavaScript). Here it demonstrates the creation and export of a simple function.

EXPLANATIONS:
- The (module) directive defines the WebAssembly module.
- The function (func $getNumber (result i32) (i32.const 42)) defines a parameterless function that returns the value 42.
- The directive (export "getNumber" (func $getNumber)) makes the function accessible from outside the module.
- There are no imports or defined memory, making the module very simple.
- To use this module, you must compile the WAT code into a binary .wasm file and then load it in an environment that supports WebAssembly.

Example Code: wasm

(module
  ;; Definition of an exported function called 'getNumber'
  ;; that returns a 32-bit integer with value 42
  (func $getNumber (result i32)
    i32.const 42
  )
  ;; Exporting the function so it can be called from outside
  (export "getNumber" (func $getNumber))
)
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

Complete Example

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Hello World with WebAssembly Text Format (WAT)</title>
</head>
<body>
  <h1>WebAssembly Text Format (WAT) Example</h1>
  <button id="run">Run getNumber</button>
  <p>Result: <span id="result">-</span></p>

  <script type="module">
    // Original WAT code as a string
    const watCode = `(module
  ;; Definition of an exported function called 'getNumber'
  ;; that returns a 32-bit integer with value 42
  (func $getNumber (result i32)
    i32.const 42
  )
  ;; Exporting the function so it can be called from outside
  (export "getNumber" (func $getNumber))
)`;

    // Function to compile WAT to WASM binary using WebAssembly.instantiateStreaming is not possible here,
    // so we use the WebAssembly Text Format to binary compilation via WebAssembly.compileStreaming or a tool.
    // Since browsers don't support direct WAT compilation, we use the WebAssembly.compile with a precompiled binary.

    // For demonstration, we will use the WebAssembly Text Format compiled to binary using the WebAssembly JavaScript API
    // by using the WebAssembly.compile with a Uint8Array of the binary.
    // But since we only have WAT, we need to convert it to binary first.
    // To keep it simple and self-contained, we will use the WebAssembly.instantiateStreaming with a base64 encoded wasm binary.

    // Precompiled wasm binary of the above WAT (compiled externally):
    const wasmBase64 = 'AGFzbQEAAAABBwFgAAF/AwIBAAELBQEDZ2V0TnVtYmVyAAAK';

    // Decode base64 to Uint8Array
    function base64ToUint8Array(base64) {
      const binaryString = atob(base64);
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
      return bytes;
    }

    const wasmBytes = base64ToUint8Array(wasmBase64);

    let wasmInstance;

    async function loadWasm() {
      const { instance } = await WebAssembly.instantiate(wasmBytes);
      wasmInstance = instance;
    }

    document.getElementById('run').addEventListener('click', async () => {
      if (!wasmInstance) {
        await loadWasm();
      }
      // Call the exported function getNumber
      const result = wasmInstance.exports.getNumber();
      document.getElementById('result').textContent = result;
    });
  </script>
</body>
</html>

What do you need?

WebAssembly module in text format (WAT) containing:
  • Exported function 'getNumber' that returns an integer 42
  • No external dependencies or imports
Execution environment:
  • Modern browser or Node.js environment with WebAssembly support
  • No specific hardware configuration required
Links and configurations:
  • To run the module, you need to compile the WAT to wasm binary (e.g., with wat2wasm)
  • The wasm module can be loaded and instantiated via JavaScript
  • No external libraries or software dependencies required