From 3ca6a66d9b6275e0d2423cdbab1f9ada150165d6 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Fri, 19 Apr 2024 17:10:36 +0200 Subject: [PATCH] Add lua read_string() function --- src/script.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/script.c b/src/script.c index 9490057..da2a9a1 100644 --- a/src/script.c +++ b/src/script.c @@ -266,6 +266,59 @@ static bool match_regex(regex_t *regex) return false; } +// lua: ret,string = read_string(size, timeout) +static int read_string(lua_State *L) +{ + int size = lua_tointeger(L, 1); + int timeout = lua_tointeger(L, 2); + int ret = 0; + + char *buffer = malloc(size); + if (buffer == NULL) + { + ret = -3; // Read buffer allocation failed + goto error; + } + + if (timeout == 0) + { + timeout = -1; // Wait forever + } + + ssize_t bytes_read = read_poll(device_fd, buffer, size, timeout); + if (bytes_read < 0) + { + ret = -1; // Read error + goto error; + } + else if (bytes_read == 0) + { + ret = -2; // Timeout + goto error; + } + + for (ssize_t i=0; i