Special method ‣ valueOf() - chung-leong/zigar GitHub Wiki

This method creates a "JavaScript version" of a Zig data object. Structs become regular JavaScript objects. Arrays and vectors become regular JavaScript arrays. Enums become strings. Pointers become the valueOf() of their targets.

This function is able to handle recursive references. Example:

const std = @import("std");

const NodeType = enum { red, blue };
pub const Node = struct {
    type: NodeType,
    id: i64,
    parent: ?*const @This() = null,
    children: ?[]*const @This() = null,
};

pub fn getRoot(allocator: std.mem.Allocator) !*const Node {
    const root: *Node = try allocator.create(Node);
    root.* = .{ .type = .red, .id = 0 };
    const child1: *Node = try allocator.create(Node);
    child1.* = .{ .type = .blue, .id = 1, .parent = root };
    const child2: *Node = try allocator.create(Node);
    child2.* = .{ .type = .blue, .id = 2, .parent = root };
    const children = try allocator.alloc(*const Node, 2);
    children[0] = child1;
    children[1] = child2;
    root.children = children;
    return root;
}
import { getRoot } from './valueof-example-1.zig';

const root = getRoot();
console.log(root.valueOf());
<ref *1> {
  type: 'red',
  id: 0n,
  parent: null,
  children: [
    { type: 'blue', id: 1n, parent: [Circular *1], children: null },
    { type: 'blue', id: 2n, parent: [Circular *1], children: null }
  ]
}

This method is useful when you need to dump an object into the development console.

Text strings

Text strings stored in []u8 will normally be converted to an array of bytes:

pub const Avenger = struct {
    real_name: []const u8,
    superhero_name: []const u8,
    age: u32,
};

pub const spiderman: Avenger = .{
    .real_name = "Peter Parker",
    .superhero_name = "Spiderman",
    .age = 17,
};
import { spiderman } from './string-example-1.zig';

console.log(spiderman.valueOf());
{
  real_name: [
     80, 101, 116, 101, 114,
     32,  80,  97, 114, 107,
    101, 114
  ],
  superhero_name: [
     83, 112, 105, 100,
    101, 114, 109,  97,
    110
  ],
  age: 17
}

If you define @"meta(zigar).isFieldString()" and inform Zigar that a field should be interpreted as a string, the result of valueOf() will reflect this:

pub const Avenger = struct {
    real_name: []const u8,
    superhero_name: []const u8,
    age: u32,
};

pub const spiderman: Avenger = .{
    .real_name = "Peter Parker",
    .superhero_name = "Spiderman",
    .age = 17,
};

pub const @"meta(zigar)" = struct {
    pub fn isFieldString(comptime T: type, comptime field_name: []const u8) bool {
        _ = field_name;
        return switch (T) {
            Avenger => true,
            else => false,
        };
    }
};
import { spiderman } from './string-example-2.zig';

console.log(spiderman.valueOf());
{ real_name: 'Peter Parker', superhero_name: 'Spiderman', age: 17 }

Special methods | Text string

⚠️ **GitHub.com Fallback** ⚠️