aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorThijs Schreijer <thijs@thijsschreijer.nl>2024-05-07 19:28:34 +0200
committerThijs Schreijer <thijs@thijsschreijer.nl>2024-05-07 19:56:24 +0200
commit9a526bb260ae70b3f63652b48436dd0e7d3d5bb0 (patch)
tree909063b35c59e0d267c42dfd822ba8fa1d749756 /src
parentb41df538c72c7e9a26f9ff08f2668769c8d1a1d1 (diff)
downloadluasystem-9a526bb260ae70b3f63652b48436dd0e7d3d5bb0.tar.gz
luasystem-9a526bb260ae70b3f63652b48436dd0e7d3d5bb0.tar.bz2
luasystem-9a526bb260ae70b3f63652b48436dd0e7d3d5bb0.zip
fix(readkey): add proper error handling
Diffstat (limited to 'src')
-rw-r--r--src/term.c29
1 files changed, 25 insertions, 4 deletions
diff --git a/src/term.c b/src/term.c
index 9a9967d..715ec4a 100644
--- a/src/term.c
+++ b/src/term.c
@@ -697,22 +697,43 @@ before calling this function. Otherwise it will block.
697@function readkey 697@function readkey
698@treturn[1] integer the key code of the key that was pressed 698@treturn[1] integer the key code of the key that was pressed
699@treturn[2] nil if no key was pressed 699@treturn[2] nil if no key was pressed
700@treturn[3] nil on error
701@treturn[3] string error message
702@treturn[3] int errnum (on posix)
700*/ 703*/
701static int lst_readkey(lua_State *L) { 704static int lst_readkey(lua_State *L) {
702#ifdef _WIN32 705#ifdef _WIN32
703 if (_kbhit()) { 706 if (_kbhit()) {
704 lua_pushinteger(L, _getch()); 707 int ch = _getch();
708 if (ch == EOF) {
709 // Error handling for end-of-file or read error
710 lua_pushnil(L);
711 lua_pushliteral(L, "_getch error");
712 return 2;
713 }
714 lua_pushinteger(L, (unsigned char)ch);
705 return 1; 715 return 1;
706 } 716 }
707 return 0; 717 return 0;
708 718
709#else 719#else
710 char ch; 720 char ch;
711 if (read(STDIN_FILENO, &ch, 1) > 0) { 721 ssize_t bytes_read = read(STDIN_FILENO, &ch, 1);
712 lua_pushinteger(L, ch); 722 if (bytes_read > 0) {
723 lua_pushinteger(L, (unsigned char)ch);
713 return 1; 724 return 1;
725
726 } else if (bytes_read == 0) {
727 return 0; // End of file or stream closed
728
729 } else {
730 if (errno == EAGAIN || errno == EWOULDBLOCK) {
731 // Resource temporarily unavailable, no data available to read
732 return 0;
733 } else {
734 return pusherror(L, "read error");
735 }
714 } 736 }
715 return 0;
716 737
717#endif 738#endif
718} 739}