Skip to content

Commit

Permalink
Implement push_into_stack/from_stack for Option<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
khvzak committed Mar 28, 2024
1 parent fa217d3 commit f67f864
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,15 @@ impl<'lua, T: IntoLua<'lua>> IntoLua<'lua> for Option<T> {
None => Ok(Nil),
}
}

#[inline]
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
match self {
Some(val) => val.push_into_stack(lua)?,
None => ffi::lua_pushnil(lua.state()),
}
Ok(())
}
}

impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Option<T> {
Expand All @@ -1073,4 +1082,13 @@ impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Option<T> {
value => Ok(Some(T::from_lua(value, lua)?)),
}
}

#[inline]
unsafe fn from_stack(idx: c_int, lua: &'lua Lua) -> Result<Self> {
if ffi::lua_isnil(lua.state(), idx) != 0 {
Ok(None)
} else {
Ok(Some(T::from_stack(idx, lua)?))
}
}
}
18 changes: 18 additions & 0 deletions tests/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,3 +453,21 @@ fn test_bstring_from_lua_buffer() -> Result<()> {

Ok(())
}

#[test]
fn test_option_into_from_lua() -> Result<()> {
let lua = Lua::new();

// Direct conversion
let v = Some(42);
let v2 = v.into_lua(&lua)?;
assert_eq!(v, v2.as_i32());

// Push into stack / get from stack
let f = lua.create_function(|_, v: Option<i32>| Ok(v))?;
assert_eq!(f.call::<_, Option<i32>>(Some(42))?, Some(42));
assert_eq!(f.call::<_, Option<i32>>(Option::<i32>::None)?, None);
assert_eq!(f.call::<_, Option<i32>>(())?, None);

Ok(())
}

0 comments on commit f67f864

Please sign in to comment.