diff --git a/node-graph/gcore/src/graphic_element.rs b/node-graph/gcore/src/graphic_element.rs index 915d82344..131c6c04b 100644 --- a/node-graph/gcore/src/graphic_element.rs +++ b/node-graph/gcore/src/graphic_element.rs @@ -551,3 +551,53 @@ impl From for GraphicElement { pub trait ToGraphicElement { fn to_graphic_element(&self) -> GraphicElement; } + +/// Returns the value at the specified index in the collection. +/// If that index has no value, the type's default value is returned. +#[node_macro::node(category("General"))] +fn index( + _: impl Ctx, + /// The collection of data, such as a list or table. + #[implementations( + Vec, + Vec>, + Vec, Vec, + Vec, + VectorDataTable, + RasterDataTable, + GraphicGroupTable, + )] + collection: T, + /// The index of the item to retrieve, starting from 0 for the first item. + index: u32, +) -> T::Output +where + T::Output: Clone + Default, +{ + collection.at_index(index as usize).unwrap_or_default() +} + +pub trait AtIndex { + type Output; + fn at_index(&self, index: usize) -> Option; +} +impl AtIndex for Vec { + type Output = T; + + fn at_index(&self, index: usize) -> Option { + self.get(index).cloned() + } +} +impl AtIndex for Instances { + type Output = Instances; + + fn at_index(&self, index: usize) -> Option { + let mut result_table = Self::default(); + if let Some(row) = self.instance_ref_iter().nth(index) { + result_table.push(row.to_instance_cloned()); + Some(result_table) + } else { + None + } + } +}