Search code examples
gokeyboard

Golang loop until key pressed


I'm using Go and I need to be able to run a loop until a certain key is pressed. Are there any libraries or is there any functionality that allows this to happen? I just need to detect if a key is down on each iteration of the loop. I've tried using azul3d, but it wasn't quite what I was looking for...

This is what I'm hoping for:

exit := false
for !exit {
    exit = watcher.Down(keyboard.Space)
}

or something similar


Solution

  • Use keyboard with its termbox backend, like this:

    package main
    
    import "github.com/julienroland/keyboard-termbox"
    import "fmt"
    import term "github.com/nsf/termbox-go"
    
    func main() {
        running := true
        err := term.Init()
        if err != nil {
            panic(err)
        }
    
        defer term.Close()
    
        kb := termbox.New()
        kb.Bind(func() {
            fmt.Println("pressed space!")
            running = false
        }, "space")
    
        for running {
            kb.Poll(term.PollEvent())
        }
    
    }