Implement As/FromLua for Option<T>

This commit is contained in:
SeanOMik 2024-02-25 20:49:05 -05:00
parent beea6c33fc
commit 936ea60634
Signed by: SeanOMik
GPG Key ID: FEC9E2FC15235964
2 changed files with 25 additions and 1 deletions

View File

@ -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<T> {
fn as_lua(self, lua: &'a State) -> crate::Result<Value<'a>> {
match self {
Some(v) => v.as_lua(lua),
None => Ok(Value::Nil)
}
}
}
impl<'a, T: FromLua<'a>> FromLua<'a> for Option<T> {
fn from_lua(lua: &'a State, val: Value<'a>) -> crate::Result<Self> {
if val.is_nil() {
Ok(None)
} else {
Ok(Some(T::from_lua(lua, val)?))
}
}
}

View File

@ -330,7 +330,6 @@ impl<'a> From<Vec<Value<'a>>> for ValueVec<'a> {
}
}
impl<'a> FromLuaStack<'a> for ValueVec<'a> {
unsafe fn from_lua_stack(state: &'a State) -> crate::Result<Self> {
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<T: AsLua<'a>>(&mut self, lua: &'a State, val: T) -> crate::Result<()> {
let val = val.as_lua(lua)?;
self.push_back(val);
Ok(())
}
}
impl<'a> From<Value<'a>> for ValueVec<'a> {