summaryrefslogtreecommitdiff
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.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.
@function readkey
@treturn[1] integer the key code of the key that was pressed
@treturn[2] nil if no key was pressed
+@treturn[3] nil on error
+@treturn[3] string error message
+@treturn[3] int errnum (on posix)
*/
static int lst_readkey(lua_State *L) {
#ifdef _WIN32
if (_kbhit()) {
- lua_pushinteger(L, _getch());
+ int ch = _getch();
+ if (ch == EOF) {
+ // Error handling for end-of-file or read error
+ lua_pushnil(L);
+ lua_pushliteral(L, "_getch error");
+ return 2;
+ }
+ lua_pushinteger(L, (unsigned char)ch);
return 1;
}
return 0;
#else
char ch;
- if (read(STDIN_FILENO, &ch, 1) > 0) {
- lua_pushinteger(L, ch);
+ ssize_t bytes_read = read(STDIN_FILENO, &ch, 1);
+ if (bytes_read > 0) {
+ lua_pushinteger(L, (unsigned char)ch);
return 1;
+
+ } else if (bytes_read == 0) {
+ return 0; // End of file or stream closed
+
+ } else {
+ if (errno == EAGAIN || errno == EWOULDBLOCK) {
+ // Resource temporarily unavailable, no data available to read
+ return 0;
+ } else {
+ return pusherror(L, "read error");
+ }
}
- return 0;
#endif
}