From 936ea606343dbcf5321b4b988de65daf8769ff3f Mon Sep 17 00:00:00 2001 From: SeanOMik Date: Sun, 25 Feb 2024 20:49:05 -0500 Subject: [PATCH] Implement As/FromLua for Option --- src/lib.rs | 19 +++++++++++++++++++ src/value.rs | 7 ++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index f4917ee..0ddc591 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -173,4 +173,23 @@ impl<'a> PushToLuaStack<'a> for bool { let v = self.as_lua(state)?; v.push_to_lua_stack(state) } +} + +impl<'a, T: AsLua<'a>> AsLua<'a> for Option { + fn as_lua(self, lua: &'a State) -> crate::Result> { + match self { + Some(v) => v.as_lua(lua), + None => Ok(Value::Nil) + } + } +} + +impl<'a, T: FromLua<'a>> FromLua<'a> for Option { + fn from_lua(lua: &'a State, val: Value<'a>) -> crate::Result { + if val.is_nil() { + Ok(None) + } else { + Ok(Some(T::from_lua(lua, val)?)) + } + } } \ No newline at end of file diff --git a/src/value.rs b/src/value.rs index 8d943ff..9c5bd85 100755 --- a/src/value.rs +++ b/src/value.rs @@ -330,7 +330,6 @@ impl<'a> From>> for ValueVec<'a> { } } - impl<'a> FromLuaStack<'a> for ValueVec<'a> { unsafe fn from_lua_stack(state: &'a State) -> crate::Result { let s = state.state_ptr(); @@ -390,6 +389,12 @@ impl<'a> ValueVec<'a> { T::from_lua_value_vec(lua, self) .map(|t| Some(t)) } + + pub fn push_val>(&mut self, lua: &'a State, val: T) -> crate::Result<()> { + let val = val.as_lua(lua)?; + self.push_back(val); + Ok(()) + } } impl<'a> From> for ValueVec<'a> {