I'm pretty new to Haskell, so I'm looking for a simple-ish way to detect keypresses, rather than using getLine
.
If anyone knows any libraries, or some trick to doing this, it would be great!
And if there is a better place to ask this, please direct me there, I'd appreciate it.
If you don't want blocking you can use hReady
to detect whether a key has been pressed yet. This is useful for games where you want the program to run and pick up a key press whenever it has happened without pausing the game.
Here's a convenience function I use for this:
ifReadyDo :: Handle -> IO a -> IO (Maybe a)
ifReadyDo hnd x = hReady hnd >>= f
where f True = x >>= return . Just
f _ = return Nothing
Which can be used like this:
stdin `ifReadyDo` getChar
Returning a Maybe
that is Just
if a key was pressed and Nothing
otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With