Add Lua::replace_registry_value

This commit is contained in:
Alex Orlenko 2022-02-14 20:51:24 +00:00
parent 9a5a341e44
commit 6190427f37
No known key found for this signature in database
GPG Key ID: 4C150C250863B96D
2 changed files with 38 additions and 0 deletions

View File

@ -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.
///

View File

@ -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::<i32>(42)?;
lua.replace_registry_value(&key, "new value")?;
assert_eq!(lua.registry_value::<String>(&key)?, "new value");
Ok(())
}
#[test]
fn test_lua_registry_hash() -> Result<()> {
let lua = Lua::new();