From 56c378f5f9a3389ed3e7184f1d7d2b92758bbbb8 Mon Sep 17 00:00:00 2001 From: yabu76 Date: Sun, 2 Nov 2025 10:15:16 +0900 Subject: [PATCH] Add multipul patterns function tio.expects() to Lua API Add tio.expects() which has a table of patterns in the arguments to support "OR" pattern waiting. The return values of tio.expects() are: 1st: index of the matched pattern in the table. nil if unmatched. 2nd: a table of captures if one of the patterns are matched. nil if any of the patterns are unmatched and timeout. 3rd: all received strings in tio.expects() to treat the strings after match. Add all received string to tio.expect()'s return values too. For example, idx, captures, all_received = tio.expects( {"\nOK", "\nERROR"}, 1000 ) captures, all_received = tio.expect( "\nPROMPT>", 1000 ) --- src/script.c | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/script.c b/src/script.c index 76b5933..13d20da 100644 --- a/src/script.c +++ b/src/script.c @@ -60,14 +60,32 @@ static char script_init[] = " local str = ''\n" " while true do\n" " local c = tio.read(1, timeout)\n" -" if c then\n" -" str = str .. c\n" -" if string.match(str, pattern) then\n" -" return string.match(str, pattern)\n" -" end\n" -" else\n" +" if c == nil then\n" " return nil, str\n" " end\n" +" str = str .. c\n" +" if string.match(str, pattern) then\n" +" return string.match(str, pattern), str\n" +" end\n" +" end\n" +"end\n" +"tio.expects = function(patterns, timeout)\n" +" local str = ''\n" +" if type(patterns) ~= 'table' then\n" +" patterns = { patterns }\n" +" end\n" +" while true do\n" +" local c = tio.read(1, timeout)\n" +" if c == nil then\n" +" return nil, nil, str\n" +" end\n" +" str = str .. c\n" +" for idx, pat in ipairs(patterns) do\n" +" local captured = { string.match(str, pat) }\n" +" if #captured > 0 then\n" +" return idx, captured, str\n" +" end\n" +" end\n" " end\n" "end\n" "tio.alwaysecho = true\n"