From 6190427f373b24a12ab527704fab56561da11316 Mon Sep 17 00:00:00 2001 From: Alex Orlenko Date: Mon, 14 Feb 2022 20:51:24 +0000 Subject: [PATCH] Add Lua::replace_registry_value --- src/lua.rs | 27 +++++++++++++++++++++++++++ tests/tests.rs | 11 +++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/lua.rs b/src/lua.rs index 0138de7..fcef729 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -1777,6 +1777,33 @@ impl Lua { Ok(()) } + /// Replaces a value in the Lua registry by its `RegistryKey`. + /// + /// See [`create_registry_value`] for more details. + /// + /// [`create_registry_value`]: #method.create_registry_value + pub fn replace_registry_value<'lua, T: ToLua<'lua>>( + &'lua self, + key: &RegistryKey, + t: T, + ) -> Result<()> { + let t = t.to_lua(self)?; + unsafe { + let _sg = StackGuard::new(self.state); + check_stack(self.state, 4)?; + + self.push_value(t)?; + // It must be safe to replace the value without triggering memory error + ffi::lua_rawseti( + self.state, + ffi::LUA_REGISTRYINDEX, + key.registry_id as Integer, + ); + + Ok(()) + } + } + /// Returns true if the given `RegistryKey` was created by a `Lua` which shares the underlying /// main state with this `Lua` instance. /// diff --git a/tests/tests.rs b/tests/tests.rs index 4b92d4f..6c6b132 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -800,6 +800,17 @@ fn test_drop_registry_value() -> Result<()> { Ok(()) } +#[test] +fn test_replace_registry_value() -> Result<()> { + let lua = Lua::new(); + + let key = lua.create_registry_value::(42)?; + lua.replace_registry_value(&key, "new value")?; + assert_eq!(lua.registry_value::(&key)?, "new value"); + + Ok(()) +} + #[test] fn test_lua_registry_hash() -> Result<()> { let lua = Lua::new();