impl TypeBuilder::is_iterable

This commit is contained in:
Tristan Guichaoua 2022-08-10 14:00:43 +02:00
parent ba84b12612
commit 0046c3a330
2 changed files with 38 additions and 0 deletions

View File

@ -283,6 +283,20 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> {
} }
} }
impl<'a, T> TypeBuilder<'a, T>
where
T: Variant + Clone + IntoIterator,
<T as IntoIterator>::Item: Variant + Clone,
{
/// Register an type iterator.
/// This is an advanced API.
#[inline(always)]
pub fn is_iterable(&mut self) -> &mut Self {
self.engine.register_iterator::<T>();
self
}
}
impl<'a, T: Variant + Clone> Drop for TypeBuilder<'a, T> { impl<'a, T: Variant + Clone> Drop for TypeBuilder<'a, T> {
#[inline] #[inline]
fn drop(&mut self) { fn drop(&mut self) {

View File

@ -45,10 +45,21 @@ fn build_type() -> Result<(), Box<EvalAltResult>> {
} }
} }
impl IntoIterator for Vec3 {
type Item = INT;
type IntoIter = std::array::IntoIter<INT, 3>;
fn into_iter(self) -> Self::IntoIter {
<[INT; 3] as IntoIterator>::into_iter([self.x, self.y, self.z])
}
}
impl CustomType for Vec3 { impl CustomType for Vec3 {
fn build(mut builder: TypeBuilder<Self>) { fn build(mut builder: TypeBuilder<Self>) {
builder builder
.with_name("Vec3") .with_name("Vec3")
.is_iterable()
.with_fn("vec3", Self::new) .with_fn("vec3", Self::new)
.with_get_set("x", Self::get_x, Self::set_x) .with_get_set("x", Self::get_x, Self::set_x)
.with_get_set("y", Self::get_y, Self::set_y) .with_get_set("y", Self::get_y, Self::set_y)
@ -117,6 +128,19 @@ fn build_type() -> Result<(), Box<EvalAltResult>> {
)?, )?,
Vec3::new(5, 6, 7), Vec3::new(5, 6, 7),
); );
assert_eq!(
engine.eval::<INT>(
"
let sum = 0;
let v = vec3(1, 2, 3);
for i in v {
sum += i;
}
sum
",
)?,
6,
);
Ok(()) Ok(())
} }