From 47ac8cae09c788fc0a2bde709a07addd7da5443a Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Thu, 6 Feb 2025 08:35:34 +0100 Subject: [PATCH] Expose some JS regexp functions to Lua --- common/space_lua/stdlib/string.ts | 21 +++++++++++++-------- common/space_lua/stdlib/string_test.lua | 11 ++++++++++- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/common/space_lua/stdlib/string.ts b/common/space_lua/stdlib/string.ts index ef7e0195..b00e3281 100644 --- a/common/space_lua/stdlib/string.ts +++ b/common/space_lua/stdlib/string.ts @@ -58,16 +58,15 @@ export const stringApi = new LuaTable({ return String.fromCharCode(...args); }), find: new LuaBuiltinFunction( - (_sf, s: string, pattern: string, init?: number, plain?: boolean) => { + (_sf, s: string, pattern: string, init?: number) => { init = init ?? 1; - plain = plain ?? false; const result = s.slice(init - 1).match(pattern); if (!result) { return new LuaMultiRes([]); } return new LuaMultiRes([ - result.index! + 1, - result.index! + result[0].length, + result.index! + init, + result.index! + init + result[0].length, ]); }, ), @@ -218,9 +217,15 @@ export const stringApi = new LuaTable({ const regex = new RegExp(pattern); const result = s.match(regex); return jsToLuaValue(result); - // if (!result) { - // return new LuaMultiRes([]); - // } - // return new LuaMultiRes(result.slice(1)); + }), + match_regex_all: new LuaBuiltinFunction((_sf, s: string, pattern: string) => { + const regex = new RegExp(pattern, "g"); + return () => { + const match = regex.exec(s); + if (!match) { + return; + } + return jsToLuaValue(match); + }; }), }); diff --git a/common/space_lua/stdlib/string_test.lua b/common/space_lua/stdlib/string_test.lua index 11c4febf..fbe3d57a 100644 --- a/common/space_lua/stdlib/string_test.lua +++ b/common/space_lua/stdlib/string_test.lua @@ -69,7 +69,7 @@ assert(result == "XXllo", "Empty capture replacement failed") -- Patterns with magic characters result = string.gsub("hello.world", "%.", "-") -assert(result == "hello-world", "Magic character replacement failed") +assert(result == "hello-world", "Magic character replacement failed") -- Test string.match local m1, m2 = string.match("hello world", "(h)(ello)") @@ -141,3 +141,12 @@ assert_equal(year, "14") local word = string.match("The quick brown fox", "%s*(%w+)%s*") assert_equal(word, "The") +-- Test match_regex_all +local matches = {} +for match in string.match_regex_all("hellolllbl", "(l+)") do + table.insert(matches, match) +end +assert_equal(#matches, 3) +assert_equal(matches[1][1], "ll") +assert_equal(matches[2][1], "lll") +assert_equal(matches[3][1], "l")