diff options
author | Alex Orlenko <zxteam@protonmail.com> | 2024-03-28 18:18:08 +0000 |
---|---|---|
committer | Alex Orlenko <zxteam@protonmail.com> | 2024-03-28 18:18:08 +0000 |
commit | f67f8646ae799bac59392e6e9a5b81330bedbd0c (patch) | |
tree | ed3a748410704ca37f33d8bf3b6b25aef1673df1 | |
parent | fa217d3706ebebfd1519743c3e620a940c218967 (diff) | |
download | mlua-f67f8646ae799bac59392e6e9a5b81330bedbd0c.zip |
Implement `push_into_stack`/`from_stack` for `Option<T>`
-rw-r--r-- | src/conversion.rs | 18 | ||||
-rw-r--r-- | tests/conversion.rs | 18 |
2 files changed, 36 insertions, 0 deletions
diff --git a/src/conversion.rs b/src/conversion.rs index 8ca8fe8..dc12c0b 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -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> { @@ -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)?)) + } + } } diff --git a/tests/conversion.rs b/tests/conversion.rs index ad2c09a..5897d75 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<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(()) +} |