diff options
| author | Thijs <thijs@thijsschreijer.nl> | 2023-11-16 09:09:54 +0100 |
|---|---|---|
| committer | Thijs Schreijer <thijs@thijsschreijer.nl> | 2024-04-30 09:28:01 +0200 |
| commit | bd994461ef7c2553da9a6945c685152bad50eb8f (patch) | |
| tree | 28adc32712f00a200a34357e731a570bf1a359dc /examples/spinner.lua | |
| parent | 47c24eed0191f8f72646be63dee94ac2b35eb062 (diff) | |
| download | luasystem-bd994461ef7c2553da9a6945c685152bad50eb8f.tar.gz luasystem-bd994461ef7c2553da9a6945c685152bad50eb8f.tar.bz2 luasystem-bd994461ef7c2553da9a6945c685152bad50eb8f.zip | |
feat(term): getting/setting terminal config flags
Diffstat (limited to 'examples/spinner.lua')
| -rw-r--r-- | examples/spinner.lua | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/examples/spinner.lua b/examples/spinner.lua new file mode 100644 index 0000000..5526adc --- /dev/null +++ b/examples/spinner.lua | |||
| @@ -0,0 +1,64 @@ | |||
| 1 | local sys = require("system") | ||
| 2 | |||
| 3 | print [[ | ||
| 4 | |||
| 5 | An example to display a spinner, whilst a long running task executes. | ||
| 6 | |||
| 7 | ]] | ||
| 8 | |||
| 9 | |||
| 10 | -- start make backup, to auto-restore on exit | ||
| 11 | sys.autotermrestore() | ||
| 12 | -- configure console | ||
| 13 | sys.setconsoleflags(io.stdin, sys.getconsoleflags(io.stdin) - sys.CIF_ECHO_INPUT - sys.CIF_LINE_INPUT) | ||
| 14 | local of = sys.tcgetattr(io.stdin) | ||
| 15 | sys.tcsetattr(io.stdin, sys.TCSANOW, { lflag = of.lflag - sys.L_ICANON - sys.L_ECHO }) | ||
| 16 | sys.setnonblock(io.stdin, true) | ||
| 17 | |||
| 18 | |||
| 19 | |||
| 20 | local function hideCursor() | ||
| 21 | io.write("\27[?25l") | ||
| 22 | io.flush() | ||
| 23 | end | ||
| 24 | |||
| 25 | local function showCursor() | ||
| 26 | io.write("\27[?25h") | ||
| 27 | io.flush() | ||
| 28 | end | ||
| 29 | |||
| 30 | local function left(n) | ||
| 31 | io.write("\27[",n or 1,"D") | ||
| 32 | io.flush() | ||
| 33 | end | ||
| 34 | |||
| 35 | |||
| 36 | |||
| 37 | local spinner do | ||
| 38 | local spin = [[|/-\]] | ||
| 39 | local i = 1 | ||
| 40 | spinner = function() | ||
| 41 | hideCursor() | ||
| 42 | io.write(spin:sub(i, i)) | ||
| 43 | left() | ||
| 44 | i = i + 1 | ||
| 45 | if i > #spin then i = 1 end | ||
| 46 | |||
| 47 | if sys.keypressed() then | ||
| 48 | sys.readkey() -- consume key pressed | ||
| 49 | io.write(" "); | ||
| 50 | left() | ||
| 51 | showCursor() | ||
| 52 | return true | ||
| 53 | else | ||
| 54 | return false | ||
| 55 | end | ||
| 56 | end | ||
| 57 | end | ||
| 58 | |||
| 59 | io.stdout:write("press any key to stop the spinner... ") | ||
| 60 | while not spinner() do | ||
| 61 | sys.sleep(0.1) | ||
| 62 | end | ||
| 63 | |||
| 64 | print("Done!") | ||
