diff options
| author | Thijs Schreijer <thijs@thijsschreijer.nl> | 2024-06-20 22:43:06 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-06-20 22:43:06 +0200 |
| commit | c1a64c1b75f97cef97965b3bd9a941564a6270bd (patch) | |
| tree | b9a92dff6462abd5859c3c76f19748fad5d6c025 /examples/terminalsize.lua | |
| parent | 47c24eed0191f8f72646be63dee94ac2b35eb062 (diff) | |
| parent | b87e6d6d762ee823e81dd7a8984f330eb4018fd8 (diff) | |
| download | luasystem-c1a64c1b75f97cef97965b3bd9a941564a6270bd.tar.gz luasystem-c1a64c1b75f97cef97965b3bd9a941564a6270bd.tar.bz2 luasystem-c1a64c1b75f97cef97965b3bd9a941564a6270bd.zip | |
Merge pull request #21 from lunarmodules/terminal
Diffstat (limited to 'examples/terminalsize.lua')
| -rw-r--r-- | examples/terminalsize.lua | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/examples/terminalsize.lua b/examples/terminalsize.lua new file mode 100644 index 0000000..105a415 --- /dev/null +++ b/examples/terminalsize.lua | |||
| @@ -0,0 +1,37 @@ | |||
| 1 | local sys = require("system") | ||
| 2 | |||
| 3 | sys.autotermrestore() -- set up auto restore of terminal settings on exit | ||
| 4 | |||
| 5 | -- setup Windows console to handle ANSI processing | ||
| 6 | sys.setconsoleflags(io.stdout, sys.getconsoleflags(io.stdout) + sys.COF_VIRTUAL_TERMINAL_PROCESSING) | ||
| 7 | sys.setconsoleflags(io.stdin, sys.getconsoleflags(io.stdin) + sys.CIF_VIRTUAL_TERMINAL_INPUT) | ||
| 8 | |||
| 9 | -- setup Posix to disable canonical mode and echo | ||
| 10 | local of_attr = sys.tcgetattr(io.stdin) | ||
| 11 | sys.setnonblock(io.stdin, true) | ||
| 12 | sys.tcsetattr(io.stdin, sys.TCSANOW, { | ||
| 13 | lflag = of_attr.lflag - sys.L_ICANON - sys.L_ECHO, -- disable canonical mode and echo | ||
| 14 | }) | ||
| 15 | |||
| 16 | |||
| 17 | -- generate string to move cursor horizontally | ||
| 18 | -- positive goes right, negative goes left | ||
| 19 | local function cursor_move_horiz(n) | ||
| 20 | if n == 0 then | ||
| 21 | return "" | ||
| 22 | end | ||
| 23 | return "\27[" .. (n > 0 and n or -n) .. (n > 0 and "C" or "D") | ||
| 24 | end | ||
| 25 | |||
| 26 | |||
| 27 | local rows, cols | ||
| 28 | print("Change the terminal window size, press any key to exit") | ||
| 29 | while not sys.readansi(0.2) do -- use readansi to not leave stray bytes in the input buffer | ||
| 30 | local nrows, ncols = sys.termsize() | ||
| 31 | if rows ~= nrows or cols ~= ncols then | ||
| 32 | rows, cols = nrows, ncols | ||
| 33 | local text = "Terminal size: " .. rows .. "x" .. cols .. " " | ||
| 34 | io.write(text .. cursor_move_horiz(-#text)) | ||
| 35 | io.flush() | ||
| 36 | end | ||
| 37 | end | ||
