Fix type metamethod and test case for regex

This commit is contained in:
Filip Tibell 2024-04-20 23:38:06 +02:00
parent 96eed54a65
commit 7a46f12c02
No known key found for this signature in database
4 changed files with 13 additions and 5 deletions

View file

@ -79,10 +79,13 @@ impl LuaUserData for LuaCaptures {
Ok(new)
});
methods.add_meta_method(LuaMetaMethod::Type, |_, _, ()| Ok("RegexCaptures"));
methods.add_meta_method(LuaMetaMethod::Len, |_, this, ()| Ok(this.num_captures()));
methods.add_meta_method(LuaMetaMethod::ToString, |_, this, ()| {
Ok(format!("RegexCaptures({})", this.num_captures()))
});
}
fn add_fields<'lua, F: LuaUserDataFields<'lua, Self>>(fields: &mut F) {
fields.add_meta_field(LuaMetaMethod::Type, "RegexCaptures");
}
}

View file

@ -40,10 +40,11 @@ impl LuaUserData for LuaMatch {
fields.add_field_method_get("finish", |_, this| Ok(this.end));
fields.add_field_method_get("len", |_, this| Ok(this.range().len()));
fields.add_field_method_get("text", |_, this| Ok(this.slice().to_string()));
fields.add_meta_field(LuaMetaMethod::Type, "RegexMatch");
}
fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_meta_method(LuaMetaMethod::Type, |_, _, ()| Ok("RegexMatch"));
methods.add_meta_method(LuaMetaMethod::Len, |_, this, ()| Ok(this.range().len()));
methods.add_meta_method(LuaMetaMethod::ToString, |_, this, ()| {
Ok(format!("RegexMatch({})", this.slice()))

View file

@ -65,9 +65,12 @@ impl LuaUserData for LuaRegex {
},
);
methods.add_meta_method(LuaMetaMethod::Type, |_, _, ()| Ok("Regex"));
methods.add_meta_method(LuaMetaMethod::ToString, |_, this, ()| {
Ok(format!("Regex({})", this.inner.as_str()))
});
}
fn add_fields<'lua, F: LuaUserDataFields<'lua, Self>>(fields: &mut F) {
fields.add_meta_field(LuaMetaMethod::Type, "Regex");
}
}

View file

@ -10,6 +10,7 @@ local mtch = re:find("1337 wow")
assert(tostring(mtch) == "RegexMatch(1337)")
assert(typeof(mtch) == "RegexMatch")
local captures = re:captures("1337 125600 wow! 1984 0")
assert(tostring(captures) == "RegexCaptures(3)")
local re2 = regex.new("([0-9]+) ([0-9]+) wow! ([0-9]+) ([0-9]+)")
local captures = re2:captures("1337 125600 wow! 1984 0")
assert(tostring(captures) == "RegexCaptures(4)")
assert(typeof(captures) == "RegexCaptures")