nvim_oxi_luajit/
state.rs

1use core::cell::OnceCell;
2
3use crate::ffi::State;
4
5thread_local! {
6    static LUA: OnceCell<*mut State> = const { 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 State) {
14    LUA.with(|lua| {
15        let _ = lua.set(lstate);
16    });
17}
18
19/// Executes a function with access to the Lua state.
20///
21/// NOTE: this will segfault if the Lua state has not been initialized by
22/// calling [`init`].
23pub unsafe fn with_state<F, R>(fun: F) -> R
24where
25    F: FnOnce(*mut State) -> R,
26{
27    LUA.with(move |lstate| fun(*lstate.get().unwrap()))
28}