Short math notation, casting, clarity of math expressions

now we’re cooking

3 Likes

Yes! I had too many accidents in other languages. The explicitness of Zig can be a bit painful sometimes. But I like that pain more than a bug. I did not write one numeric bug yet using Zig!

4 Likes

Those numerical bugs are pretty easy to write unit tests for so I’m not sure the possibility of making a mistake is worse than the cure here. I’ve only written such code once in Zig tho so I might get happier with the current state if I use it more.

However, I really like the suggestion of automatic coercion to ints from certain functions!

This might not be the suggestion you’re looking for, but have you thought about making your own @builtin helper functions? My current project is riddled with typecasting, and I’ve thought about defining a few to make things cleaner to read and understand.

For example, something like this:

const x = @as(usize, @intFromFloat(position.x)

could be:

const x = @usizeFromF32(position.x)

Naming these is hard though, and I haven’t done it myself yet, but it would be less noisy for common typecasting.

The second I imported Raylib I felt that helpers might be inevitable.

 raylib.drawRectangle(
    @as(i32, @intCast(x)) * @as(i32, @intFromFloat(cell_width)),
    @as(i32, @intCast(y)) * @as(i32, @intFromFloat(cell_height)),
    @as(i32, @intFromFloat(cell_width)),
    @as(i32, @intFromFloat(cell_height)),
    color,
);

You can create regular helper functions, but builtins are just those that come with the language. So what do you mean with creating builtins yourself, do you mean adding more builtins for specific type casting to the language?

I suppose I think of them like globally accessible functions. You are right, they would just be a helper to replace chained builtins for typecasting.

So more like

const x = usizeFromF32(position.x)

You would have to import and declare the function in the files where you use them (because Zig doesn’t have globally available functions, builtins are available everywhere but they are part of the language), so you would need something like this:

const helpers = @import("helpers");
const usizeFromF32 = helpers.usizeFromF32;

Personally I think that is good enough. You also could do something like:

const h = @import("helpers");
...
const x = h.usizeFromF32(position.x)
1 Like