Golang循环,直到按下键
问题描述:
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
我正在使用Go,并且我需要能够运行循环,直到按下某个键为止。 是否有任何库或任何允许这种情况发生的功能? 我只需要在循环的每次迭代中检测键是否为 down em>即可。 我已经尝试过使用azul3d,但这并不是我想要的... p>
这就是我所希望的: p>
或类似的
div> exit:= false
for!exit {
exit = watcher.Down(keyboard.Space)
}
code> pre>
答
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())
}
}
答
I believe you can use this fmt.Scanln()
instead