aboutsummaryrefslogtreecommitdiff
path: root/examples/read.lua
diff options
context:
space:
mode:
Diffstat (limited to 'examples/read.lua')
-rw-r--r--examples/read.lua70
1 files changed, 70 insertions, 0 deletions
diff --git a/examples/read.lua b/examples/read.lua
new file mode 100644
index 0000000..4b57b54
--- /dev/null
+++ b/examples/read.lua
@@ -0,0 +1,70 @@
1local sys = require "system"
2
3print [[
4
5This example shows how to do a non-blocking read from the cli.
6
7]]
8
9-- setup Windows console to handle ANSI processing
10local of_in = sys.getconsoleflags(io.stdin)
11local of_out = sys.getconsoleflags(io.stdout)
12sys.setconsoleflags(io.stdout, sys.getconsoleflags(io.stdout) + sys.COF_VIRTUAL_TERMINAL_PROCESSING)
13sys.setconsoleflags(io.stdin, sys.getconsoleflags(io.stdin) + sys.CIF_VIRTUAL_TERMINAL_INPUT)
14
15-- setup Posix terminal to use non-blocking mode, and disable line-mode
16local of_attr = sys.tcgetattr(io.stdin)
17local of_block = sys.getnonblock(io.stdin)
18sys.setnonblock(io.stdin, true)
19sys.tcsetattr(io.stdin, sys.TCSANOW, {
20 lflag = of_attr.lflag - sys.L_ICANON - sys.L_ECHO, -- disable canonical mode and echo
21})
22
23-- cursor sequences
24local get_cursor_pos = "\27[6n"
25
26
27
28print("Press a key, or 'A' to get cursor position, 'ESC' to exit")
29while true do
30 local key, keytype
31
32 -- wait for a key
33 while not key do
34 key, keytype = sys.readansi(math.huge)
35 end
36
37 if key == "A" then io.write(get_cursor_pos); io.flush() end
38
39 -- check if we got a key or ANSI sequence
40 if keytype == "char" then
41 -- just a key
42 local b = key:byte()
43 if b < 32 then
44 key = "." -- replace control characters with a simple "." to not mess up the screen
45 end
46
47 print("you pressed: " .. key .. " (" .. b .. ")")
48 if b == 27 then
49 print("Escape pressed, exiting")
50 break
51 end
52
53 elseif keytype == "ansi" then
54 -- we got an ANSI sequence
55 local seq = { key:byte(1, #key) }
56 print("ANSI sequence received: " .. key:sub(2,-1), "(bytes: " .. table.concat(seq, ", ")..")")
57
58 else
59 print("unknown key type received: " .. tostring(keytype))
60 end
61end
62
63
64
65-- Clean up afterwards
66sys.setnonblock(io.stdin, false)
67sys.setconsoleflags(io.stdout, of_out)
68sys.setconsoleflags(io.stdin, of_in)
69sys.tcsetattr(io.stdin, sys.TCSANOW, of_attr)
70sys.setnonblock(io.stdin, of_block)