Shrink unsafe block in `Lua::load_from_function` and update doc

This commit is contained in:
Alex Orlenko 2021-07-13 16:03:50 +01:00
parent 97bd288f56
commit 8a7e546c66
No known key found for this signature in database
GPG Key ID: 4C150C250863B96D
1 changed files with 23 additions and 24 deletions

View File

@ -509,8 +509,11 @@ impl Lua {
res res
} }
/// Calls the Lua function `func` with the string `modname` as an argument, sets /// Loads module `modname` into an existing Lua state using the specified entrypoint
/// the call result to `package.loaded[modname]` and returns copy of the result. /// function.
///
/// Internally calls the Lua function `func` with the string `modname` as an argument,
/// sets the call result to `package.loaded[modname]` and returns copy of the result.
/// ///
/// If `package.loaded[modname]` value is not nil, returns copy of the value without /// If `package.loaded[modname]` value is not nil, returns copy of the value without
/// calling the function. /// calling the function.
@ -530,14 +533,14 @@ impl Lua {
S: AsRef<[u8]> + ?Sized, S: AsRef<[u8]> + ?Sized,
T: FromLua<'lua>, T: FromLua<'lua>,
{ {
unsafe { let loaded = unsafe {
let _sg = StackGuard::new(self.state); let _sg = StackGuard::new(self.state);
check_stack(self.state, 3)?; check_stack(self.state, 3)?;
protect_lua(self.state, 0, 1, |state| { protect_lua(self.state, 0, 1, |state| {
ffi::luaL_getsubtable(state, ffi::LUA_REGISTRYINDEX, cstr!("_LOADED")); ffi::luaL_getsubtable(state, ffi::LUA_REGISTRYINDEX, cstr!("_LOADED"));
})?; })?;
let loaded = Table(self.pop_ref()); Table(self.pop_ref())
};
let modname = self.create_string(modname)?; let modname = self.create_string(modname)?;
let value = match loaded.raw_get(modname.clone())? { let value = match loaded.raw_get(modname.clone())? {
@ -553,7 +556,6 @@ impl Lua {
}; };
T::from_lua(value, self) T::from_lua(value, self)
} }
}
/// Consumes and leaks `Lua` object, returning a static reference `&'static Lua`. /// Consumes and leaks `Lua` object, returning a static reference `&'static Lua`.
/// ///
@ -1084,11 +1086,8 @@ impl Lua {
/// # Safety /// # Safety
/// This function is unsafe because provides a way to execute unsafe C function. /// This function is unsafe because provides a way to execute unsafe C function.
pub unsafe fn create_c_function(&self, func: ffi::lua_CFunction) -> Result<Function> { pub unsafe fn create_c_function(&self, func: ffi::lua_CFunction) -> Result<Function> {
let _sg = StackGuard::new(self.state); check_stack(self.state, 1)?;
check_stack(self.state, 3)?; ffi::lua_pushcfunction(self.state, func);
protect_lua(self.state, 0, 1, |state| {
ffi::lua_pushcfunction(state, func);
})?;
Ok(Function(self.pop_ref())) Ok(Function(self.pop_ref()))
} }