Filter out nil objects when inserting in Arrays and Dictionarys

This commit is contained in:
Riccardo Mazzarini 2025-03-19 16:44:30 +01:00
parent b70748c56e
commit 0424a1ad26
No known key found for this signature in database
GPG key ID: 38165222613796F5
2 changed files with 40 additions and 21 deletions

View file

@ -56,7 +56,10 @@ impl Array {
where
V: Into<Object>,
{
self.0.push(value.into());
let value = value.into();
if !value.is_nil() {
self.0.push(value);
}
}
/// Removes an `Object` from the `Array` and returns it.
@ -89,15 +92,21 @@ impl DerefMut for Array {
}
}
impl<T: Into<Object>> Extend<T> for Array {
#[inline]
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for value in iter {
self.push(value);
}
}
}
impl<T: Into<Object>> FromIterator<T> for Array {
#[inline]
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Self(
iter.into_iter()
.map(Into::into)
.filter(|obj| obj.is_some())
.collect(),
)
let mut array = Self::new();
array.extend(iter);
array
}
}
@ -185,7 +194,9 @@ impl lua::Pushable for Array {
lua_createtable(lstate, self.len() as _, 0);
for (idx, obj) in self.into_iter().enumerate() {
for (idx, obj) in
self.into_iter().filter(|obj| !obj.is_nil()).enumerate()
{
obj.push(lstate)?;
lua_rawseti(lstate, -2, (idx + 1) as _);
}

View file

@ -90,8 +90,10 @@ impl Dictionary {
K: Into<crate::String>,
V: Into<Object>,
{
let pair = KeyValuePair { key: key.into(), value: value.into() };
self.0.push(pair);
let value = value.into();
if !value.is_nil() {
self.0.push(KeyValuePair { key: key.into(), value });
}
}
/// Returns `true` if the dictionary contains no elements.
@ -231,6 +233,19 @@ where
}
}
impl<K, V> Extend<(K, V)> for Dictionary
where
K: Into<crate::String>,
V: Into<Object>,
{
#[inline]
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
for (key, value) in iter {
self.insert(key, value);
}
}
}
impl<K, V> FromIterator<(K, V)> for Dictionary
where
K: Into<crate::String>,
@ -238,16 +253,9 @@ where
{
#[inline]
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
Self(
iter.into_iter()
.filter_map(|(k, v)| {
let value = v.into();
value
.is_some()
.then(|| KeyValuePair { key: k.into(), value })
})
.collect(),
)
let mut dict = Self::new();
dict.extend(iter);
dict
}
}
@ -407,7 +415,7 @@ impl lua::Pushable for Dictionary {
lua_createtable(lstate, 0, self.len() as _);
for (key, obj) in self {
for (key, obj) in self.into_iter().filter(|(_, obj)| !obj.is_nil()) {
lua_pushlstring(lstate, key.as_ptr(), key.len());
obj.push(lstate)?;
lua_rawset(lstate, -3);