diff --git a/src/conversion.rs b/src/conversion.rs index 8ca8fe86..dc12c0bd 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -1063,6 +1063,15 @@ impl<'lua, T: IntoLua<'lua>> IntoLua<'lua> for Option { 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 { @@ -1073,4 +1082,13 @@ impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Option { value => Ok(Some(T::from_lua(value, lua)?)), } } + + #[inline] + unsafe fn from_stack(idx: c_int, lua: &'lua Lua) -> Result { + if ffi::lua_isnil(lua.state(), idx) != 0 { + Ok(None) + } else { + Ok(Some(T::from_stack(idx, lua)?)) + } + } } diff --git a/tests/conversion.rs b/tests/conversion.rs index ad2c09ad..5897d75e 100644 --- a/tests/conversion.rs +++ b/tests/conversion.rs @@ -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| Ok(v))?; + assert_eq!(f.call::<_, Option>(Some(42))?, Some(42)); + assert_eq!(f.call::<_, Option>(Option::::None)?, None); + assert_eq!(f.call::<_, Option>(())?, None); + + Ok(()) +}