Skip to content

Instantly share code, notes, and snippets.

@tomoe-mami
Last active June 28, 2019 01:15
Show Gist options
  • Save tomoe-mami/e351851c3672371da0b4925b812a3a0d to your computer and use it in GitHub Desktop.
Save tomoe-mami/e351851c3672371da0b4925b812a3a0d to your computer and use it in GitHub Desktop.
"Press any key" example in Lua with POSIX module.
local bit = require "bit"
local termio = require "posix.termio"
local unistd = require "posix.unistd"
local inspect = require "inspect"
local t = termio.tcgetattr(unistd.STDIN_FILENO)
local o_vmin, o_vtime, o_lflag = t.cc[termio.VMIN], t.cc[termio.VTIME], t.lflag
io.stdout:write("Press any key... ")
-- blocking read for 1 byte
t.cc[termio.VMIN] = 1
t.cc[termio.VTIME] = 0
t.lflag = bit.band(t.lflag, bit.bnot(bit.bor(termio.ECHO, termio.ICANON)))
termio.tcsetattr(unistd.STDIN_FILENO, termio.TCSANOW, t)
local ch = io.read(1)
-- in case of escape sequence, do polling read to get the rest of bytes
if ch == "\27" then
t.cc[termio.VMIN] = 0
termio.tcsetattr(unistd.STDIN_FILENO, termio.TCSANOW, t)
repeat
local b = io.read(1)
if b then
ch = ch .. b
end
until not b
end
t.cc[termio.VMIN] = o_vmin
t.cc[termio.VTIME] = o_vtime
t.lflag = o_lflag
termio.tcsetattr(unistd.STDIN_FILENO, termio.TCSANOW, t)
print("\nYou pressed: " .. inspect(ch))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment