wasm4 icon indicating copy to clipboard operation
wasm4 copied to clipboard

wasm4.zig: print wrappers with comptime formatting and type safety

Open Ruulul opened this issue 2 years ago • 4 comments

add functions print, that prints on console, printText, that wraps the text function, and printBuffer, that prints on an arbitrary buffer. allows leveraging custom formatters on custom types, type safety, and use the error handling for ergonomics.

Ruulul avatar Nov 17 '23 18:11 Ruulul

the stdlib already has functions to print to a buffer and with an arguably better API. im also a little confused about the other functions youve added, if i know the extra_len that i want, why not just create an array myself and use the buffer print function?

xdBronch avatar Nov 21 '23 07:11 xdBronch

again didnt know about this one handy function

about the why... I just realized it was being too common to write out a block, create a scoped buffer, print to that buffer, then send the buffer to the proper function (w4.trace or w4.text)

and on a second note, I dont like to need to manually count characters to know the needed buffer size, and it is not viable to do the std.debug trick and make a [1024]u8 buffer on wasm4, so I settled to an offset based on the fmt string len

mostly I wanted a way to be able to do this kind of pattern in an ergonomic way:

w4.textPrint(1, "Gen:\n{}", 135, 10, .{generation}) catch {
  w4.text("Gen:\nXe?", 135, 20);
};

I am curious tho of what is the expected way to handle printing in general... without a wrapper I would need to do something like...

{
  const fmt = "Gen:\n{}";
  var buffer: [@as(comptime_int, fmt.len) + 1]u8 = undefined;
  w4.text(std.fmt.bufPrint(&buffer, fmt, .{generation}) catch "Gen:\nXe?", 135, 20);
}

I understand tho if you see this as not general enough for the wasm4.zig file. I just thought it is a pretty common need to want to use a formatter, and it is unpleasant to need to manually count characters to know the proper offsets

Ruulul avatar Nov 21 '23 11:11 Ruulul

I just realized I can write a simple comptime logic to make all calls use the same buffer, but I am not sure if this is worthywhile

Ruulul avatar Nov 21 '23 12:11 Ruulul

I think this is better handled by users since you both need to specify how big you want the buffer to be and it adds a dependency on std.

JerwuQu avatar Apr 18 '24 19:04 JerwuQu