Hello all, I was wondering what an approach might be for polling a buffer for a key-down event? Would I use std.io?
I have a pause
function…
- Current tragic state:
- read first byte of user input from
\n
terminated string (sigh)
q
→ exit program
- otherwise → continue execution
- Preferred awesome state:
- poll key-down buffer for key-down event
ESC
→ exit program
- other key down → continue execution
- no input received → perform some other action (in my use case - animate ansi text fx), then return to polling
what might be an approach? I suppose a key-down buffer is optional at this point, could make the end-user hold key-down until key-down polling finds it…but would be nice if they don’t have to.
pub fn pause() void {
//todo - poll / read a keystroke w/out echo, \n etc
emit(color_reset);
emit("Press return to continue...");
var b: u8 = undefined;
b = stdin.readByte() catch undefined;
if (b == 'q') {
//exit cleanly
complete();
std.os.exit(0);
}
}
GitHub Src
What is the catch undefined
for? It seems to me like it should be catch unreachable
if it is impossible to happen, otherwise it should be catch 0
or something that has guaranteed behavior in your control flow. I know undefined
is typically 0’s or 0xA’s, but it could be anything, including ‘q’. Unless you literally mean, “I don’t care at all what the value is or what behavior we choose. YOLO”
1 Like
Hello,
I’m trying to do something similar as well the best thing I found was they way the project zig-spoon by Leon Plickat does it in the demos for his library.
Something along the line of:
// Open tty
var tty = try std.fs.cwd().openFile("/dev/tty", .{ .mode = .read_write });
// No idea
var fds: [1]std.os.pollfd = undefined;
// No idea 2
fds[0] = .{
.fd = tty.handle,
.events = std.os.POLL.IN,
.revents = undefined,
};
// Buffer to holf the user input
var buffer: [16]u8 = undefined;
while (run) {
_ = try std.os.poll(&fds, -1);
_ = try std.os.read(tty.handle, &buffer);
input.parse(&buffer);
...
I think you should be able to do this with stdio instead of tty.
But I am a beginner and don’t fully understand that code honestly
but maybe it helps you go in the right direction.