luajit_bindings/state.rs
1use once_cell::unsync::OnceCell;
2
3use crate::ffi::lua_State;
4
5thread_local! {
6 static LUA: OnceCell<*mut lua_State> = OnceCell::new();
7}
8
9/// Initializes the Lua state.
10///
11/// NOTE: this function **must** be called before calling any other function
12/// exposed by this crate or there will be segfaults.
13pub unsafe fn init(lstate: *mut lua_State) {
14 LUA.with(|lua| lua.set(lstate).unwrap_unchecked());
15}
16
17/// Executes a function with access to the Lua state.
18///
19/// NOTE: this will segfault if the Lua state has not been initialized by
20/// calling [`init`].
21pub unsafe fn with_state<F, R>(fun: F) -> R
22where
23 F: FnOnce(*mut lua_State) -> R,
24{
25 LUA.with(move |lstate| fun(*lstate.get().unwrap_unchecked()))
26}