summaryrefslogtreecommitdiff
path: root/src/value.rs
diff options
context:
space:
mode:
authorAlex Orlenko <zxteam@protonmail.com>2020-01-06 23:59:50 +0000
committerAlex Orlenko <zxteam@protonmail.com>2020-01-07 00:03:03 +0000
commit5eec0ef56ba710e8bcd2e4f32ade865c7b2d23d6 (patch)
tree7eff34c340e9dbfd49ef3acb6f3a36348b72a3f3 /src/value.rs
parent831161bfda4fb5bfea306e8ebec6db508a0884c8 (diff)
downloadmlua-5eec0ef56ba710e8bcd2e4f32ade865c7b2d23d6.zip
Implement PartialEq trait for Value (and subtypes)
Add equals() method to compare values optionally invoking __eq.
Diffstat (limited to 'src/value.rs')
-rw-r--r--src/value.rs46
1 files changed, 46 insertions, 0 deletions
diff --git a/src/value.rs b/src/value.rs
index c3eab89..1ab5399 100644
--- a/src/value.rs
+++ b/src/value.rs
@@ -2,6 +2,7 @@ use std::iter::{self, FromIterator};
use std::{slice, str, vec};
use crate::error::{Error, Result};
+use crate::ffi;
use crate::function::Function;
use crate::lua::Lua;
use crate::string::String;
@@ -61,6 +62,51 @@ impl<'lua> Value<'lua> {
Value::UserData(_) | Value::Error(_) => "userdata",
}
}
+
+ /// Compares two values for equality.
+ ///
+ /// Equality comparisons do not convert strings to numbers or vice versa.
+ /// Tables, Functions, Threads, and Userdata are compared by reference:
+ /// two objects are considered equal only if they are the same object.
+ ///
+ /// If Tables or Userdata have `__eq` metamethod then mlua will try to invoke it.
+ /// The first value is checked first. If that value does not define a metamethod
+ /// for `__eq`, then mlua will check the second value.
+ /// Then mlua calls the metamethod with the two values as arguments, if found.
+ pub fn equals<T: AsRef<Self>>(&self, other: T) -> Result<bool> {
+ match (self, other.as_ref()) {
+ (Value::Table(a), Value::Table(b)) => a.equals(b),
+ (Value::UserData(a), Value::UserData(b)) => a.equals(b),
+ _ => Ok(self == other.as_ref()),
+ }
+ }
+}
+
+impl<'lua> PartialEq for Value<'lua> {
+ fn eq(&self, other: &Self) -> bool {
+ match (self, other) {
+ (Value::Nil, Value::Nil) => true,
+ (Value::Boolean(a), Value::Boolean(b)) => a == b,
+ (Value::LightUserData(a), Value::LightUserData(b)) => a == b,
+ (Value::Integer(a), Value::Integer(b)) => *a == *b,
+ (Value::Integer(a), Value::Number(b)) => *a as ffi::lua_Number == *b,
+ (Value::Number(a), Value::Integer(b)) => *a == *b as ffi::lua_Number,
+ (Value::Number(a), Value::Number(b)) => *a == *b,
+ (Value::String(a), Value::String(b)) => a == b,
+ (Value::Table(a), Value::Table(b)) => a == b,
+ (Value::Function(a), Value::Function(b)) => a == b,
+ (Value::Thread(a), Value::Thread(b)) => a == b,
+ (Value::UserData(a), Value::UserData(b)) => a == b,
+ _ => false,
+ }
+ }
+}
+
+impl<'lua> AsRef<Value<'lua>> for Value<'lua> {
+ #[inline]
+ fn as_ref(&self) -> &Self {
+ self
+ }
}
/// Trait for types convertible to `Value`.