Expose some JS regexp functions to Lua

pull/1232/head
Zef Hemel 2025-02-06 08:35:34 +01:00
parent 3344845d1f
commit 47ac8cae09
2 changed files with 23 additions and 9 deletions

View File

@ -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);
};
}),
});

View File

@ -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")