Skip to main content

luaur_rt/
vector.rs

1//! The [`Vector`] type (Luau `vector`). Mirrors `mlua::Vector`.
2//!
3//! Unlike the reference-typed handles, a Luau vector is a small *value* type
4//! (its components live inline in the VM `TValue`, not on the GC heap), so
5//! [`Vector`] is a plain `Copy` struct of its components — no registry ref
6//! needed. luaur is built with `LUA_VECTOR_SIZE == 3`, so [`Vector`] is
7//! 3-dimensional here (mlua's `luau-vector4` path is N/A — see
8//! `tests/ATTRIBUTION.md`).
9
10use std::fmt;
11
12/// A Luau vector type.
13///
14/// Mirrors `mlua::Vector`. luaur is a 3-dimensional-vector build
15/// (`LUA_VECTOR_SIZE == 3`), so this is always a 3-component vector.
16#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd)]
17pub struct Vector(pub(crate) [f32; Self::SIZE]);
18
19impl fmt::Display for Vector {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        write!(f, "vector({}, {}, {})", self.x(), self.y(), self.z())
22    }
23}
24
25impl Vector {
26    /// The number of components. luaur is a 3-wide build.
27    pub(crate) const SIZE: usize = 3;
28
29    /// Creates a new vector.
30    ///
31    /// Mirrors `mlua::Vector::new`.
32    pub const fn new(x: f32, y: f32, z: f32) -> Self {
33        Self([x, y, z])
34    }
35
36    /// Creates a new vector with all components set to `0.0`.
37    ///
38    /// Mirrors `mlua::Vector::zero`.
39    pub const fn zero() -> Self {
40        Self([0.0; Self::SIZE])
41    }
42
43    /// Returns 1st component of the vector.
44    pub const fn x(&self) -> f32 {
45        self.0[0]
46    }
47
48    /// Returns 2nd component of the vector.
49    pub const fn y(&self) -> f32 {
50        self.0[1]
51    }
52
53    /// Returns 3rd component of the vector.
54    pub const fn z(&self) -> f32 {
55        self.0[2]
56    }
57}
58
59impl PartialEq<[f32; Self::SIZE]> for Vector {
60    #[inline]
61    fn eq(&self, other: &[f32; Self::SIZE]) -> bool {
62        self.0 == *other
63    }
64}