low_luajit/lua/state.rs
1use core::ptr;
2
3use crate::{LuaState, ffi::{self, lua_State}};
4
5/// State handling functions.
6impl LuaState {
7 /* Not yet...
8 /// Creates a new valid and independent Lua state.
9 ///
10 /// This state will use the standard C `realloc` function as its allocator.
11 ///
12 /// # Safety
13 ///
14 /// While there is nothing inherently unsafe about creating a new `LuaState`,
15 /// using the state without a protected environment could end badly in case a Lua error is triggered:
16 /// at best, Rust simply aborts abruptly...but I've had segmentation faults happen sometimes too.
17 #[inline]
18 pub unsafe fn new_unchecked() -> Self {
19 let ptr = unsafe { luaL_newstate() };
20 assert!(!ptr.is_null(), "cannot create new Lua state: memory allocation error");
21 Self(ptr)
22 }*/
23
24 /// Wraps a pre-existing raw [`lua_State`] pointer.
25 ///
26 /// # Safety
27 ///
28 /// `ptr` **must** be a valid pointer of an already existing state, as all other methods will assume it to be so.
29 ///
30 /// Additionally, there must not be an existing `LuaState` that is already using this pointer.
31 #[must_use]
32 pub const unsafe fn from_ptr(ptr: *mut lua_State) -> Self {
33 Self(ptr)
34 }
35
36 /// Returns the wrapped raw [`lua_State`] pointer.
37 ///
38 /// The caller must ensure that the `LuaState` outlives the pointer this function returns, or else it will end up dangling.
39 ///
40 /// The returned pointer should also not be passed to functions that might invalidate the `LuaState` (like [`lua_close`]).
41 ///
42 /// [`lua_close`]: ./ffi/fn.lua_close.html
43 #[must_use]
44 pub const fn as_ptr(&self) -> *mut lua_State {
45 self.0
46 }
47
48 /// Destroys all objects and frees all dynamic memory of the state.
49 ///
50 /// # Safety
51 ///
52 /// Can only be called if this `LuaState` is not being used anywhere else.
53 ///
54 /// If your crate is a Lua module, this function must *not* return back to the Lua interpreter (as it would no longer exist).
55 #[inline]
56 pub unsafe fn close(self) {
57 // SAFETY: self.0 is always valid and the caller must make sure that the LuaState is not used anywhere else.
58 unsafe { ffi::lua_close(self.0); }
59 }
60
61 /// Returns a reference to a number that represents the version of Lua.
62 ///
63 /// For LuaJIT, this should always returns `501` (which represents 5.1, the Lua version LuaJIT is based on).
64 #[inline]
65 pub fn version() -> &'static f64 {
66 // SAFETY: lua_version doesn't actually use the pointer given to it and always returns a valid pointer to a static f64.
67 unsafe { &*ffi::lua_version(ptr::null_mut()) }
68 }
69}