Skip to content

Commit 00328b0

Browse files
committed
Protect Lua::push_c_function for Lua <5.2
1 parent 928d94d commit 00328b0

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/state.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1286,8 +1286,24 @@ impl Lua {
12861286
/// This function is unsafe because provides a way to execute unsafe C function.
12871287
pub unsafe fn create_c_function(&self, func: ffi::lua_CFunction) -> Result<Function> {
12881288
let lua = self.lock();
1289-
ffi::lua_pushcfunction(lua.ref_thread(), func);
1290-
Ok(Function(lua.pop_ref_thread()))
1289+
if cfg!(any(feature = "lua54", feature = "lua53", feature = "lua52")) {
1290+
ffi::lua_pushcfunction(lua.ref_thread(), func);
1291+
return Ok(Function(lua.pop_ref_thread()));
1292+
}
1293+
1294+
// Lua <5.2 requires memory allocation to push a C function
1295+
let state = lua.state();
1296+
{
1297+
let _sg = StackGuard::new(state);
1298+
check_stack(state, 3)?;
1299+
1300+
if lua.unlikely_memory_error() {
1301+
ffi::lua_pushcfunction(state, func);
1302+
} else {
1303+
protect_lua!(state, 0, 1, |state| ffi::lua_pushcfunction(state, func))?;
1304+
}
1305+
Ok(Function(lua.pop_ref()))
1306+
}
12911307
}
12921308

12931309
/// Wraps a Rust async function or closure, creating a callable Lua function handle to it.

0 commit comments

Comments
 (0)