read.lua
local sys = require "system"
print [[
This example shows how to do a non-blocking read from the cli.
]]
local of_in = sys.getconsoleflags(io.stdin)
local of_out = sys.getconsoleflags(io.stdout)
sys.setconsoleflags(io.stdout, sys.getconsoleflags(io.stdout) + sys.COF_VIRTUAL_TERMINAL_PROCESSING)
sys.setconsoleflags(io.stdin, sys.getconsoleflags(io.stdin) + sys.CIF_VIRTUAL_TERMINAL_INPUT)
local of_attr = sys.tcgetattr(io.stdin)
local of_block = sys.getnonblock(io.stdin)
sys.setnonblock(io.stdin, true)
sys.tcsetattr(io.stdin, sys.TCSANOW, {
lflag = of_attr.lflag - sys.L_ICANON - sys.L_ECHO, })
local get_cursor_pos = "\27[6n"
print("Press a key, or 'A' to get cursor position, 'ESC' to exit")
while true do
local key, keytype
while not key do
key, keytype = sys.readansi(math.huge)
end
if key == "A" then io.write(get_cursor_pos); io.flush() end
if keytype == "char" then
local b = key:byte()
if b < 32 then
key = "." end
print("you pressed: " .. key .. " (" .. b .. ")")
if b == 27 then
print("Escape pressed, exiting")
break
end
elseif keytype == "ansi" then
local seq = { key:byte(1, #key) }
print("ANSI sequence received: " .. key:sub(2,-1), "(bytes: " .. table.concat(seq, ", ")..")")
else
print("unknown key type received: " .. tostring(keytype))
end
end
sys.setnonblock(io.stdin, false)
sys.setconsoleflags(io.stdout, of_out)
sys.setconsoleflags(io.stdin, of_in)
sys.tcsetattr(io.stdin, sys.TCSANOW, of_attr)
sys.setnonblock(io.stdin, of_block)