#typeName without the namespace

1 messages · Page 1 of 1 (latest)

odd moon
#

right now, I am creating an enumeration from a list of types:

fn RegisterComponents(comptime types: anytype) type {
    const int_type = std.math.IntFittingRange(0, types.len - 1);
    var enum_fields: [types.len][]const u8 = undefined;
    var field_values: [types.len]int_type = undefined;
    for (types, 0..) |T, i| {
        enum_fields[i] = @typeName(T);
        field_values[i] = i;
    }
    return @Enum(int_type, .exhaustive, &enum_fields, &field_values);
}

const Health = struct { health: f32 };

const Components = RegisterComponents(.{Health});

pub fn main() !void {
    inline for (std.meta.fields(Components)) |field| {
        std.debug.print("{s} (value: {d})\n", .{ field.name, field.value });
    }
}

but in this case, the enumeration has the name main.Health, when ideally I want it to just be Health, is there anyway to get the name without the "namespace"?

#

(obviously, i could strip the name, was just wondering if there was a builtin function for this)

naive thunder
#

no, there's nothing for that
I think type names are 99% meant for debugging purposes, not stuff like this

odd moon
#

im just having fun with it

#

i ended up writing this abomination

fn typeNameShort(comptime T: type) []const u8 {
    const name = @typeName(T);
    comptime var last_dot = 0;
    inline for (name, 0..) |char, i| {
        if (char == '.') {
            last_dot = i;
        }
    }
    return name[last_dot + 1..];
}
naive thunder
#

why you need to rely on type names for this?

odd moon
#

is there a better way to do it? I just thought it would be fun to generate the enum

naive thunder
#

are the field names actually relevant or you just need to map the types to some kind IDs?

#

if you really need it

odd moon
#

..i see what you mean lol

#

i think something like this may be sufficient for my use case

fn RegisterComponents(comptime types: anytype) type {
    return struct {
        pub const count = types.len;

        pub fn getId(comptime T: type) usize {
            inline for (types, 0..) |component_type, i| {
                if (T == component_type) return 1 << i;
            }
            @compileError(@typeName(T) ++ " was not registered");
        }
    };
}
const Registry = RegisterComponents(.{Health, Position, Velocity, Acceleration});