diff options
author | Thijs Schreijer <thijs@thijsschreijer.nl> | 2024-05-07 19:28:34 +0200 |
---|---|---|
committer | Thijs Schreijer <thijs@thijsschreijer.nl> | 2024-05-07 19:56:24 +0200 |
commit | 9a526bb260ae70b3f63652b48436dd0e7d3d5bb0 (patch) | |
tree | 909063b35c59e0d267c42dfd822ba8fa1d749756 | |
parent | b41df538c72c7e9a26f9ff08f2668769c8d1a1d1 (diff) | |
download | luasystem-9a526bb260ae70b3f63652b48436dd0e7d3d5bb0.zip |
fix(readkey): add proper error handling
-rw-r--r-- | src/term.c | 29 |
1 files changed, 25 insertions, 4 deletions
@@ -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 } |