From 3cc2d90fda1a5dc1d8edaad2425849b83fd8372b Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Wed, 17 Apr 2024 23:38:18 +0200 Subject: [PATCH] Extend lua expect() to also return matched string --- man/tio.1.in | 5 +++++ src/script.c | 15 +++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/man/tio.1.in b/man/tio.1.in index 17871f1..5cf55d7 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -375,6 +375,11 @@ In addition to the Lua API tio makes the following functions available: Expect string - waits for string to match or timeout before continueing. Supports regular expressions. Special characters must be escaped with '\\\\'. Timeout is in milliseconds, defaults to 0 meaning it will wait forever. + +Returns 1 on successful match, 0 on timeout, or -1 on invalid regular expression. + +On successful match it also returns the match string as second return value. + .IP "\fBsend(string)" Send string. .IP "\fBmodem_send(file, protocol)" diff --git a/src/script.c b/src/script.c index 41a415b..243ae0c 100644 --- a/src/script.c +++ b/src/script.c @@ -39,6 +39,7 @@ static int device_fd; static char circular_buffer[MAX_BUFFER_SIZE]; +static char match_string[MAX_BUFFER_SIZE]; static int buffer_size = 0; // lua: sleep(seconds) @@ -233,14 +234,22 @@ void add_to_buffer(char c) bool match_regex(regex_t *regex) { char buffer[MAX_BUFFER_SIZE + 1]; // Temporary buffer for regex matching + const char *s = circular_buffer; + regmatch_t pmatch[1]; + regoff_t len; + memcpy(buffer, circular_buffer, buffer_size); buffer[buffer_size] = '\0'; // Null-terminate the buffer // Match against the regex - int ret = regexec(regex, buffer, 0, NULL, 0); + int ret = regexec(regex, buffer, 1, pmatch, 0); if (!ret) { // Match found + len = pmatch[0].rm_eo - pmatch[0].rm_so; + memcpy(match_string, s + pmatch[0].rm_so, len); + match_string[len] = '\0'; + return true; } else if (ret == REG_NOMATCH) @@ -267,6 +276,7 @@ static int expect(lua_State *L) // Resets buffer to ignore previous `expect` calls buffer_size = 0; + match_string[0] = '\0'; if ((string == NULL) || (timeout < 0)) { @@ -316,7 +326,8 @@ static int expect(lua_State *L) error: lua_pushnumber(L, ret); - return 1; + lua_pushstring(L, match_string); + return 2; } // lua: exit(code)