Skip to main content

Zig (Wasm)

Zig is a general-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.

In LiveCodes, Zig runs in the browser using WebAssembly with a WASI-compatible runtime environment.

Usage

Demo:

show code
import { createPlayground } from 'livecodes';

const options = {
"config": {
"activeEditor": "script",
"script": {
"language": "zig-wasm",
"content": "const std = @import(\"std\");\n\npub fn main() !void {\n const stdout = std.io.getStdOut().writer();\n\n const sorted_array = [_]i32{ 1, 3, 5, 7, 9, 11, 13, 15 };\n const item_to_search: i32 = 7;\n\n const result = binarySearch(i32, &sorted_array, item_to_search);\n\n if (result == -1) {\n try stdout.print(\"Result: Item not found in the array.\\n\", .{});\n } else {\n try stdout.print(\"Result: Item found at index -> {}\\n\", .{result});\n }\n}\n\nfn binarySearch(comptime T: type, arr: []const T, item: T) i32 {\n var left: usize = 0;\n var right: usize = arr.len;\n\n while (left < right) {\n const mid = left + (right - left) / 2;\n\n if (arr[mid] == item) {\n return @intCast(mid);\n }\n\n if (arr[mid] > item) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n\n return -1;\n}"
},
"mode": "simple",
"editor": "auto",
"tools": {
"status": "full"
}
}
};
createPlayground('#container', options);

Communication with JavaScript

The Zig code runs in the context of the result page. A few helper properties and methods are available in the browser global livecodes.zig object:

  • livecodes.zig.input: The initial standard input passed to the Zig code.
  • livecodes.zig.loaded: A promise that resolves when the Zig environment (WebAssembly runtime) is fully loaded (and rejects if it fails to load). Other helpers should be used after this promise resolves.
  • livecodes.zig.output: The standard output from the Zig code execution.
  • livecodes.zig.run: A function that runs the Zig code with new input. This function takes a string as input and returns a promise that resolves with an object containing the output, error, and exitCode properties.

Example:

show code
import { createPlayground } from 'livecodes';

const options = {
"template": "zig-wasm",
"params": {
"activeEditor": "markup"
}
};
createPlayground('#container', options);

Language Info

Name

zig-wasm

Aliases / Extensions

zig, zig-wasm

Editor

script

Compiler

Zig compiler in WebAssembly.

Version

Zig 0.14.0

Code Formatting

Code formatting is not currently available for Zig.

Live Reload

By default, new code changes are sent to the result page for re-evaluation without a full page reload, avoiding the need to reinitialize the Zig WebAssembly environment. This behavior can be disabled by adding the code comment // __livecodes_reload__ to the Zig code, which forces a full page reload.

This comment can be added in the hiddenContent property of the editor for embedded playgrounds.

Starter Template

https://livecodes.io/?template=zig-wasm