Zig bindings for quickjs-ng.
Requires Zig 0.16.0.
zig fetch --save=quickjs \
https://github.com/nDimensional/zig-quickjs/archive/{COMMIT}.tar.gz
https://ndimensional.github.io/zig-quickjs/
conststd=@import("std");
constquickjs=@import("quickjs");
pubfnmain() !void {
vargpa=std.heap.DebugAllocator(.{}).init;
deferstd.debug.assert(gpa.deinit() ==.ok);
constallocator=gpa.allocator();
// Create a runtime and contextconstrt=tryquickjs.Runtime.init(allocator);
deferrt.deinit();
constctx=quickjs.Context.init(rt);
deferctx.deinit();
// Evaluate JavaScriptconstresult=tryctx.eval("1 + 2", "test.js", .{});
deferctx.freeValue(result);
constnum=tryctx.toInt32(result);
std.debug.print("1 + 2 = {d}\n", .{num});
}constglobal=ctx.getGlobalObject();
deferctx.freeValue(global);
constobj=ctx.newObject();
deferctx.freeValue(obj);
// Set propertiesconstkey=ctx.newAtom("greeting");
deferctx.freeAtom(key);
constval=ctx.newString("hello");
tryctx.setProperty(obj, key, val);
deferctx.freeValue(val);
// Read propertiesconstgot=ctx.getProperty(obj, key);
deferctx.freeValue(got);constresult=tryctx.eval("(function(x, y) { return x * y; })", "test.js", .{});
deferctx.freeValue(result);
varargs= [_]quickjs.Value{ ctx.newInt32(6), ctx.newInt32(7) };
deferfor (args) |a|ctx.freeValue(a);
constret=ctx.call(result, quickjs.NULL, &args);
deferctx.freeValue(ret);
constproduct=tryctx.toInt32(ret);
std.debug.print("6 * 7 = {d}\n", .{product});constjsAdd=struct {
fncall(ctx: quickjs.Context, this_val: quickjs.Value, args: []constquickjs.Value) quickjs.Value {
if (args.len<2) returnquickjs.NULL;
consta=ctx.toInt32(args[0]) catchreturnquickjs.NULL;
constb=ctx.toInt32(args[1]) catchreturnquickjs.NULL;
returnctx.newInt32(a+b);
}
};
constfunc=ctx.newFunction("add", 2, jsAdd.call);
// setPropertyStr takes ownership of functryctx.setPropertyStr(global, "add", func);constHandler=struct {
counter: u32=0,
pubfnonInterrupt(self: *Handler) bool {
self.counter+=1;
returnself.counter>=1000;
}
};
varhandler=Handler{};
runtime.setInterruptHandler(&handler);constMyClass=struct {
pubfnfinalizer(rt: quickjs.RuntimeHandle, val: quickjs.Value) void {
// cleanup when instance is GC'd
}
};
constclass_id=runtime.newClassID();
tryruntime.newClass(class_id, .{
.name="MyClass",
.finalizer=MyClass.finalizer,
});
constobj=ctx.newObjectClass(class_id);MIT