Skip to main content

luaur_rt/
state.rs

1//! The [`Lua`] handle and the shared inner state.
2//!
3//! ## Lifetime model (mirrors mlua's `Rc<inner> + registry-key` design)
4//!
5//! [`Lua`] owns the `*mut lua_State`. The state is wrapped in an [`Rc`]
6//! ([`LuaInner`]) so that long-lived handles ([`Table`], [`Function`],
7//! [`LuaString`], the corresponding [`Value`] variants, userdata) can hold a
8//! clone of that `Rc` and keep the state alive for as long as they exist.
9//!
10//! Each such handle additionally holds a **registry reference** obtained via
11//! [`lua_ref`] (luaur's `lua_ref`/`lua_unref`). That keeps the underlying Lua
12//! value reachable by the GC, and lets the handle re-push the value onto the
13//! stack on demand. On `Drop` the handle releases its registry slot with
14//! [`lua_unref`] — but only if the state is still alive (the `Rc` keeps it so).
15//!
16//! `Lua` is single-threaded (`Rc`, so `!Send`/`!Sync`), matching mlua's
17//! non-`Send` default.
18//!
19//! ## The `send` feature
20//!
21//! Under the `send` feature (mirroring mlua) the shared interior uses
22//! [`XRc`] = `Arc` instead of `Rc`, and [`LuaInner`] / [`LuaRef`] carry a
23//! documented `unsafe impl Send`. That makes [`Lua`] and every handle `Send` so
24//! the whole VM can be **moved** to another thread. It is *not* made `Sync`: the
25//! VM is still single-threaded, the user must serialize all access, and only the
26//! ownership *transfer* crosses threads (exactly mlua's `send` contract).
27
28use std::cell::Cell;
29
30use crate::error::{Error, Result};
31use crate::sync::{MaybeSend, MaybeSync, NotSync, XRc, XWeak, NOT_SYNC};
32use crate::sys::*;
33use crate::value::Value;
34
35// Re-export the GC-control types here so they live at `luaur_rt::state::{..}`,
36// matching mlua's `mlua::state::{GcMode, GcIncParams, GcGenParams}` path.
37pub use crate::gc::{GcGenParams, GcIncParams, GcMode};
38
39/// The reference-counted, shared interior of a [`Lua`] instance.
40///
41/// Held by [`Lua`] and cloned into every long-lived handle. When the last
42/// `XRc<LuaInner>` is dropped, [`Drop`] closes the `lua_State`.
43pub(crate) struct LuaInner {
44    /// The owned VM state pointer. Never null while this `LuaInner` exists.
45    pub(crate) state: *mut lua_State,
46    /// Whether this `LuaInner` is responsible for closing the state. The
47    /// trampoline builds a *borrowed* [`Lua`] around the calling thread's
48    /// state and must not close it.
49    owned: bool,
50    /// Host type definitions accumulated via [`Lua::add_definitions`] (the
51    /// `typecheck` feature), in Luau definition-file syntax. Each registration
52    /// is appended separated by a newline; the whole buffer is fed to the
53    /// type-checker by [`Lua::check`] / [`Chunk::check`]. Uses the crate's
54    /// `RefCell` interior-mutability idiom (the VM is single-threaded).
55    #[cfg(feature = "typecheck")]
56    typecheck_defs: std::cell::RefCell<String>,
57}
58
59impl LuaInner {
60    /// Build a fresh `LuaInner`, initializing every field (including the
61    /// feature-gated `typecheck_defs` store). Used by all `Lua` constructors so
62    /// the field set stays in one place.
63    fn new(state: *mut lua_State, owned: bool) -> LuaInner {
64        LuaInner {
65            state,
66            owned,
67            #[cfg(feature = "typecheck")]
68            typecheck_defs: std::cell::RefCell::new(String::new()),
69        }
70    }
71}
72
73impl Drop for LuaInner {
74    fn drop(&mut self) {
75        if self.owned && !self.state.is_null() {
76            // Evict every per-VM thread-local entry keyed by this state before
77            // closing it, so none of them leaks one slot per state created. All
78            // are keyed by the still-valid state/global pointer here. (The serde
79            // sentinels + the sandbox saved-globals live in the state's REGISTRY,
80            // freed by `lua_close` below; here we only drop their pointer/flag
81            // bookkeeping.) These maps hold no Lua handles, so the state actually
82            // reaches this Drop — that is the whole point of not caching handles.
83            crate::app_data::clear_app_data(self.state);
84            #[cfg(feature = "async")]
85            crate::async_support::clear_async_state(self.state);
86            #[cfg(feature = "serde")]
87            crate::serde::clear_sentinels(self.state);
88            crate::interrupt::clear_interrupt(self.state);
89            crate::luau_ext::clear_vm_state(self.state);
90            // The memory map is keyed by the global-state pointer and must be
91            // dropped AFTER `lua_close` (the allocator `MemoryControl` handed to
92            // the VM as `ud` is used throughout close to free every object), so
93            // capture the key now, while the state is still valid.
94            let mem_key = unsafe { crate::memory::memory_key(self.state) };
95            unsafe {
96                // Reset the active memory category to 0 ("main") before closing.
97                // `Lua::set_memory_category` may have left a non-main category
98                // active; allocations made during teardown would otherwise be
99                // accounted to it, tripping `close_state`'s debug invariant that
100                // only category 0 is non-empty at shutdown.
101                crate::sys::lua_setmemcat(self.state, 0);
102                lua_close(self.state)
103            }
104            // Now the allocator is no longer needed: drop its control block.
105            crate::memory::clear_memory(mem_key);
106        }
107    }
108}
109
110// Under the `send` feature, allow a `Lua` (and every handle, transitively) to be
111// **moved** across threads. The raw `*mut lua_State` is `!Send`/`!Sync` by
112// default; these impls encode luaur-rt's documented contract — single-threaded
113// *use*, only *ownership transfer* across threads, never concurrent access.
114//
115// `Send` is the property we actually expose. `Sync` is needed only as an
116// internal obligation: `XRc<LuaInner>` is `Arc<LuaInner>` under the feature, and
117// `Arc<T>: Send` requires `T: Send + Sync`. We therefore mark `LuaInner` (the
118// non-public interior) `Sync`, and then keep the *public* `Lua`/handle types
119// `!Sync` with a `NotSync` phantom marker (see [`NotSync`]). Net effect: the VM
120// can be moved across threads but never shared/accessed concurrently — exactly
121// mlua's `send` contract, minus mlua's extra `Sync` (luaur-rt stays `!Sync`).
122#[cfg(feature = "send")]
123unsafe impl Send for LuaInner {}
124#[cfg(feature = "send")]
125unsafe impl Sync for LuaInner {}
126
127/// A handle to a Lua interpreter.
128///
129/// Mirrors `mlua::Lua`. Cloning produces another handle to the **same** VM
130/// (the inner state is shared via `Rc`), exactly like mlua.
131#[derive(Clone)]
132pub struct Lua {
133    pub(crate) inner: XRc<LuaInner>,
134    /// Keeps `Lua` `!Sync` under the `send` feature (the VM is move-only, never
135    /// shareable). A zero-sized `()` under the default build. See [`NotSync`].
136    pub(crate) _not_sync: NotSync,
137}
138
139impl Lua {
140    /// Create a new Lua state with the standard library opened.
141    ///
142    /// Mirrors `mlua::Lua::new`.
143    pub fn new() -> Lua {
144        // luaur's v11+ bytecode needs the default Luau flags on (see the
145        // umbrella crate's `eval`).
146        luaur_common::set_all_flags(true);
147        unsafe {
148            let state = lua_l_newstate();
149            assert!(!state.is_null(), "lua_l_newstate returned null");
150            lua_l_openlibs(state);
151            Lua {
152                inner: XRc::new(LuaInner::new(state, true)),
153                _not_sync: NOT_SYNC,
154            }
155        }
156    }
157
158    /// Create a new Lua state **without** opening the standard library.
159    ///
160    /// A deliberate deviation from mlua (which exposes `StdLib` flags); a
161    /// minimal convenience for embedders who want a clean global table.
162    pub fn new_empty() -> Lua {
163        luaur_common::set_all_flags(true);
164        let state = lua_l_newstate();
165        assert!(!state.is_null(), "lua_l_newstate returned null");
166        Lua {
167            inner: XRc::new(LuaInner::new(state, true)),
168            _not_sync: NOT_SYNC,
169        }
170    }
171
172    /// Create a new Lua state with the standard library opened, **without** the
173    /// extra safety restrictions a safe `Lua::new` would impose.
174    ///
175    /// Mirrors `mlua::Lua::unsafe_new`. In Luau there is no separate set of
176    /// "unsafe" base libraries (the `debug`/`ffi`/`package` distinction is a
177    /// Lua-5.x concept), so this is equivalent to [`Lua::new`]; it exists for
178    /// mlua signature parity.
179    ///
180    /// # Safety
181    /// Provided for parity with mlua's `unsafe_new`, which can open libraries
182    /// that allow loading native code. luaur's Luau base library does not expose
183    /// such facilities, so this is in practice as safe as [`Lua::new`]; the
184    /// `unsafe` marker is retained to match mlua's signature.
185    pub unsafe fn unsafe_new() -> Lua {
186        Lua::new()
187    }
188
189    /// Create a new Lua state opening the libraries selected by `libs`, with the
190    /// behavioral `options`. Mirrors `mlua::Lua::new_with`.
191    ///
192    /// **DEVIATION:** luaur opens the Luau base libraries as a unit, so any
193    /// non-empty `libs` opens the full standard library and [`StdLib::NONE`]
194    /// opens nothing (see [`StdLib`]). `options` is recorded on the VM (currently
195    /// only `catch_rust_panics` is observable).
196    pub fn new_with(
197        libs: crate::options::StdLib,
198        options: crate::options::LuaOptions,
199    ) -> Result<Lua> {
200        luaur_common::set_all_flags(true);
201        unsafe {
202            let state = lua_l_newstate();
203            assert!(!state.is_null(), "lua_l_newstate returned null");
204            if !libs.is_none() {
205                lua_l_openlibs(state);
206            }
207            let lua = Lua {
208                inner: XRc::new(LuaInner::new(state, true)),
209                _not_sync: NOT_SYNC,
210            };
211            lua.set_catch_rust_panics(options.catch_rust_panics);
212            Ok(lua)
213        }
214    }
215
216    /// The raw state pointer. Internal use only.
217    #[inline]
218    pub(crate) fn state(&self) -> *mut lua_State {
219        self.inner.state
220    }
221
222    /// Wrap an *already-existing* state (e.g. the thread passed into a C
223    /// trampoline) in a borrowed [`Lua`] that will **not** close it on drop.
224    ///
225    /// # Safety
226    /// `state` must be a valid `lua_State` that outlives the returned handle
227    /// and all handles cloned from it.
228    pub(crate) unsafe fn from_borrowed(state: *mut lua_State) -> Lua {
229        Lua {
230            inner: XRc::new(LuaInner::new(state, false)),
231            _not_sync: NOT_SYNC,
232        }
233    }
234
235    /// Register a value sitting at stack index `idx` in the registry and return
236    /// a [`LuaRef`] that owns the slot. Does not pop the value.
237    pub(crate) fn register_ref(&self, idx: c_int) -> LuaRef {
238        let id = unsafe { lua_ref(self.state(), idx) };
239        LuaRef {
240            inner: self.inner.clone(),
241            id: Cell::new(id),
242        }
243    }
244
245    /// Pop the top stack value and register it, returning a [`LuaRef`].
246    pub(crate) fn pop_ref(&self) -> LuaRef {
247        let r = self.register_ref(-1);
248        unsafe { lua_pop(self.state(), 1) };
249        r
250    }
251}
252
253impl Default for Lua {
254    fn default() -> Self {
255        Lua::new()
256    }
257}
258
259impl Lua {
260    /// A non-owning, weak handle to this VM. Mirrors `mlua::Lua::weak`.
261    ///
262    /// The [`WeakLua`] does not keep the VM alive; it can be upgraded back to a
263    /// strong [`Lua`] only while at least one strong handle still exists.
264    pub fn weak(&self) -> WeakLua {
265        WeakLua(XRc::downgrade(&self.inner))
266    }
267}
268
269/// A weak handle to a [`Lua`] instance. Mirrors `mlua::WeakLua`.
270///
271/// Holds a non-owning reference to the shared VM interior; upgrade it to a
272/// strong [`Lua`] with [`WeakLua::try_upgrade`] / [`WeakLua::upgrade`].
273#[derive(Clone)]
274pub struct WeakLua(pub(crate) XWeak<LuaInner>);
275
276impl WeakLua {
277    /// Try to obtain a strong [`Lua`] handle. Returns `None` if the VM has
278    /// already been destroyed. Mirrors `mlua::WeakLua::try_upgrade`.
279    pub fn try_upgrade(&self) -> Option<Lua> {
280        self.0.upgrade().map(|inner| Lua {
281            inner,
282            _not_sync: NOT_SYNC,
283        })
284    }
285
286    /// Obtain a strong [`Lua`] handle, panicking if the VM has been destroyed.
287    /// Mirrors `mlua::WeakLua::upgrade`.
288    pub fn upgrade(&self) -> Lua {
289        self.try_upgrade().expect("Lua instance is destroyed")
290    }
291}
292
293// ---------------------------------------------------------------------------
294// Public, mlua-style construction API.
295// ---------------------------------------------------------------------------
296
297use crate::callback::{create_callback_function, BoxedCallback};
298use crate::chunk::Chunk;
299use crate::function::Function;
300use crate::multi::MultiValue;
301use crate::string::LuaString;
302use crate::table::Table;
303use crate::traits::{FromLuaMulti, IntoLuaMulti};
304use crate::userdata::{AnyUserData, UserData};
305
306impl Lua {
307    /// The globals table.
308    ///
309    /// Mirrors `mlua::Lua::globals`. Returns a [`Table`] handle to the global
310    /// environment (the table reachable at `LUA_GLOBALSINDEX`).
311    pub fn globals(&self) -> Table {
312        let state = self.state();
313        unsafe {
314            // Push the globals table (a copy of the LUA_GLOBALSINDEX pseudo
315            // value) and take a ref to it.
316            lua_pushvalue(state, LUA_GLOBALSINDEX);
317            Table::from_ref(self.pop_ref())
318        }
319    }
320
321    /// Create a new, empty table.
322    ///
323    /// Mirrors `mlua::Lua::create_table` (infallible here, so no `Result`
324    /// wrapper is strictly needed — but we also provide the `_result` variant
325    /// for signature parity below).
326    pub fn create_table(&self) -> Table {
327        crate::table::create_table(self)
328    }
329
330    /// `Result`-returning alias of [`Lua::create_table`] for mlua signature
331    /// parity.
332    pub fn create_table_result(&self) -> Result<Table> {
333        Ok(self.create_table())
334    }
335
336    /// Create a Lua string from bytes/str.
337    ///
338    /// Mirrors `mlua::Lua::create_string`.
339    pub fn create_string(&self, s: impl AsRef<[u8]>) -> LuaString {
340        crate::string::create_string(self, s.as_ref())
341    }
342
343    /// Create a table and populate it from an iterator of key/value pairs.
344    ///
345    /// Mirrors `mlua::Lua::create_table_from`.
346    pub fn create_table_from<K, V, I>(&self, iter: I) -> Result<Table>
347    where
348        K: crate::traits::IntoLua,
349        V: crate::traits::IntoLua,
350        I: IntoIterator<Item = (K, V)>,
351    {
352        let t = self.create_table();
353        for (k, v) in iter {
354            t.raw_set(k, v)?;
355        }
356        Ok(t)
357    }
358
359    /// Create a sequence (1-based array) table from an iterator of values.
360    ///
361    /// Mirrors `mlua::Lua::create_sequence_from`.
362    pub fn create_sequence_from<V, I>(&self, iter: I) -> Result<Table>
363    where
364        V: crate::traits::IntoLua,
365        I: IntoIterator<Item = V>,
366    {
367        let t = self.create_table();
368        for (i, v) in iter.into_iter().enumerate() {
369            t.raw_set((i + 1) as i64, v)?;
370        }
371        Ok(t)
372    }
373
374    /// Run a full garbage-collection cycle.
375    ///
376    /// Mirrors `mlua::Lua::gc_collect` (infallible here — luaur's `lua_gc`
377    /// cannot fail for `collect`).
378    pub fn gc_collect(&self) -> Result<()> {
379        lua_gc(self.state(), lua_GCOp::LUA_GCCOLLECT as c_int, 0);
380        Ok(())
381    }
382
383    /// Create a Lua function from a Rust closure.
384    ///
385    /// Mirrors `mlua::Lua::create_function`. The closure receives `&Lua` and
386    /// the arguments converted via [`FromLuaMulti`]; its `Ok` return is
387    /// converted via [`IntoLuaMulti`]. Returning `Err` (or panicking) surfaces
388    /// as a catchable Lua error.
389    pub fn create_function<F, A, R>(&self, func: F) -> Result<Function>
390    where
391        F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
392        A: FromLuaMulti,
393        R: IntoLuaMulti,
394    {
395        let boxed: BoxedCallback = Box::new(move |lua, args| {
396            let a = A::from_lua_multi(args, lua)?;
397            let r = func(lua, a)?;
398            r.into_lua_multi(lua)
399        });
400        create_callback_function(self, boxed)
401    }
402
403    /// Create a Lua function from a Rust **mutable** closure.
404    ///
405    /// Mirrors `mlua::Lua::create_function_mut`. The closure is guarded by a
406    /// [`RefCell`](std::cell::RefCell); a re-entrant call (the callback running
407    /// Lua that calls the same callback again) surfaces as
408    /// [`Error::RecursiveMutCallback`](crate::Error::RecursiveMutCallback)
409    /// rather than allowing mutable aliasing.
410    pub fn create_function_mut<F, A, R>(&self, func: F) -> Result<Function>
411    where
412        F: FnMut(&Lua, A) -> Result<R> + MaybeSend + 'static,
413        A: FromLuaMulti,
414        R: IntoLuaMulti,
415    {
416        let func = std::cell::RefCell::new(func);
417        self.create_function(move |lua, args| {
418            let mut borrow = func
419                .try_borrow_mut()
420                .map_err(|_| Error::RecursiveMutCallback)?;
421            (borrow)(lua, args)
422        })
423    }
424
425    /// Create userdata wrapping a `T: UserData` value.
426    ///
427    /// Mirrors `mlua::Lua::create_userdata`.
428    pub fn create_userdata<T: UserData + MaybeSend + MaybeSync + 'static>(
429        &self,
430        data: T,
431    ) -> Result<AnyUserData> {
432        crate::userdata::create_userdata(self, data)
433    }
434
435    /// Create a Lua function from a Rust **async** closure (the `async`
436    /// feature).
437    ///
438    /// Mirrors `mlua::Lua::create_async_function`. The closure receives an owned
439    /// [`Lua`] and the converted arguments, and returns a `Future`. When the
440    /// resulting Lua function is called, it runs on a coroutine that **yields**
441    /// while the future is pending; a driver such as
442    /// [`Function::call_async`](crate::Function::call_async) /
443    /// [`Chunk::eval_async`](crate::Chunk::eval_async) resumes the coroutine,
444    /// polls the future, and resumes it with the result when ready.
445    ///
446    /// The executor is provided by the caller (luaur-rt is executor-agnostic,
447    /// exactly like mlua): the returned futures must be `.await`ed / polled on
448    /// the caller's runtime (e.g. tokio).
449    #[cfg(feature = "async")]
450    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
451    pub fn create_async_function<F, A, FR, R>(&self, func: F) -> Result<Function>
452    where
453        F: Fn(Lua, A) -> FR + MaybeSend + 'static,
454        A: FromLuaMulti,
455        FR: std::future::Future<Output = Result<R>> + MaybeSend + 'static,
456        R: IntoLuaMulti,
457    {
458        let callback: crate::async_support::AsyncCallback = Box::new(move |lua, args| {
459            // Convert the arguments eagerly; defer the conversion error into the
460            // future so it surfaces uniformly on the first poll.
461            let a = A::from_lua_multi(args, &lua);
462            let fut = a.map(|a| func(lua.clone(), a));
463            Box::pin(async move {
464                let r = fut?.await?;
465                r.into_lua_multi(&lua)
466            })
467        });
468        crate::async_support::create_async_callback(self, callback)
469    }
470
471    /// Creates and returns a Luau [buffer] object from a byte slice of data.
472    ///
473    /// Mirrors `mlua::Lua::create_buffer`.
474    ///
475    /// [buffer]: https://luau.org/library#buffer-library
476    pub fn create_buffer(&self, data: impl AsRef<[u8]>) -> Result<crate::buffer::Buffer> {
477        let data = data.as_ref();
478        let buffer = self.create_buffer_with_capacity(data.len())?;
479        if !data.is_empty() {
480            buffer.write_bytes(0, data);
481        }
482        Ok(buffer)
483    }
484
485    /// Creates and returns a Luau [buffer] object with the specified size.
486    ///
487    /// Size limit is 1GB. All bytes are initialized to zero. Exceeding the
488    /// limit returns a `RuntimeError` carrying a `"memory allocation error"`
489    /// message (matching mlua).
490    ///
491    /// Mirrors `mlua::Lua::create_buffer_with_capacity`.
492    ///
493    /// [buffer]: https://luau.org/library#buffer-library
494    pub fn create_buffer_with_capacity(&self, size: usize) -> Result<crate::buffer::Buffer> {
495        crate::buffer::create_buffer_with_capacity(self, size)
496    }
497
498    /// Creates and returns a Luau [`Vector`](crate::Vector) value.
499    ///
500    /// Mirrors `mlua::Lua::create_vector`. luaur is a 3-wide vector build.
501    pub fn create_vector(&self, x: f32, y: f32, z: f32) -> crate::vector::Vector {
502        crate::vector::Vector::new(x, y, z)
503    }
504
505    /// Load a chunk of Lua source for execution.
506    ///
507    /// Mirrors `mlua::Lua::load`. Returns a [`Chunk`]; finalize with
508    /// [`Chunk::exec`] / [`Chunk::eval`] / [`Chunk::into_function`].
509    pub fn load(&self, source: impl AsRef<str>) -> Chunk {
510        Chunk {
511            lua: self.clone(),
512            source: source.as_ref().to_string(),
513            name: "chunk".to_string(),
514            environment: None,
515            compiler: None,
516        }
517    }
518
519    /// Convert a Rust value into a single Lua [`Value`].
520    ///
521    /// Mirrors `mlua::Lua::pack`-ish convenience. Provided so callers can build
522    /// `Value`s without importing the trait.
523    pub fn pack(&self, value: impl crate::traits::IntoLua) -> Result<crate::value::Value> {
524        value.into_lua(self)
525    }
526
527    /// Build a [`MultiValue`] from anything `IntoLuaMulti`.
528    pub fn pack_multi(&self, values: impl IntoLuaMulti) -> Result<MultiValue> {
529        values.into_lua_multi(self)
530    }
531
532    /// Convert any `FromLuaMulti` from a packed [`MultiValue`]. Mirrors
533    /// `mlua::Lua::unpack_multi` (and `unpack` for the single-value case).
534    pub fn unpack_multi<T: FromLuaMulti>(&self, values: MultiValue) -> Result<T> {
535        T::from_lua_multi(values, self)
536    }
537
538    /// Convert a single Lua [`Value`] to a Rust value. Mirrors `mlua::Lua::unpack`.
539    pub fn unpack<T: crate::traits::FromLua>(&self, value: Value) -> Result<T> {
540        T::from_lua(value, self)
541    }
542
543    /// Coerce a [`Value`] to an integer the way Lua's `tonumber`+integer check
544    /// would (`"1"` -> `Some(1)`, `"1.5"` -> `None`, a non-numeric value ->
545    /// `None`). Mirrors `mlua::Lua::coerce_integer`.
546    pub fn coerce_integer(&self, value: Value) -> Result<Option<crate::value::Integer>> {
547        let state = self.state();
548        unsafe {
549            self.push_value(&value)?;
550            let mut isnum: c_int = 0;
551            let n = lua_tonumberx(state, -1, &mut isnum);
552            lua_pop(state, 1);
553            if isnum == 0 {
554                return Ok(None);
555            }
556            // An integral, in-range float coerces to an integer; otherwise None.
557            if n.fract() == 0.0 && n.is_finite() && n >= i64::MIN as f64 && n <= i64::MAX as f64 {
558                Ok(Some(n as i64))
559            } else {
560                Ok(None)
561            }
562        }
563    }
564
565    /// Coerce a [`Value`] to a float the way Lua's `tonumber` would. Mirrors
566    /// `mlua::Lua::coerce_number`.
567    pub fn coerce_number(&self, value: Value) -> Result<Option<crate::value::Number>> {
568        let state = self.state();
569        unsafe {
570            self.push_value(&value)?;
571            let mut isnum: c_int = 0;
572            let n = lua_tonumberx(state, -1, &mut isnum);
573            lua_pop(state, 1);
574            if isnum == 0 {
575                Ok(None)
576            } else {
577                Ok(Some(n))
578            }
579        }
580    }
581
582    /// Replace the global environment with `globals`. Mirrors
583    /// `mlua::Lua::set_globals`.
584    ///
585    /// In a sandboxed Lua state the globals table is read-only and cannot be
586    /// replaced; this returns a [`Error::RuntimeError`] in that case (matching
587    /// mlua / Luau).
588    pub fn set_globals(&self, globals: Table) -> Result<()> {
589        if self.is_sandboxed() {
590            return Err(Error::runtime(
591                "cannot change globals in a sandboxed Lua state",
592            ));
593        }
594        let state = self.state();
595        unsafe {
596            globals.push_to_stack();
597            lua_replace(state, LUA_GLOBALSINDEX);
598        }
599        Ok(())
600    }
601
602    /// Build a stack traceback string for this VM. Mirrors `mlua::Lua::traceback`.
603    ///
604    /// `msg`, if present, is prepended to the traceback; `level` selects the
605    /// starting stack level. The returned [`LuaString`] holds the traceback as
606    /// produced by `luaL_traceback`.
607    pub fn traceback(&self, msg: Option<&str>, level: usize) -> Result<LuaString> {
608        let state = self.state();
609        unsafe {
610            lua_l_traceback(state, state, msg, level as c_int);
611            // luaL_traceback pushes the resulting string onto the stack.
612            Ok(LuaString::from_ref(self.pop_ref()))
613        }
614    }
615}
616
617// ---------------------------------------------------------------------------
618// Static type-checking (the `typecheck` feature).
619//
620// luaur ships Luau's static type checker, so — unlike mlua — a script can be
621// type-checked against the host surface *before* it runs. The host surface is
622// described in Luau definition-file syntax and accumulated on the `Lua` via
623// `add_definitions`; `check` / `Chunk::check` then validate source against it.
624// ---------------------------------------------------------------------------
625#[cfg(feature = "typecheck")]
626#[cfg_attr(docsrs, doc(cfg(feature = "typecheck")))]
627impl Lua {
628    /// Register host type `definitions` (Luau definition-file syntax) so later
629    /// [`Lua::check`] / [`Chunk::check`] calls type-check against them.
630    ///
631    /// `definitions` describes the host-provided globals — the Rust functions,
632    /// values, and userdata you expose to the runtime (e.g. via
633    /// [`Lua::create_function`] / [`UserData`](crate::UserData)):
634    ///
635    /// ```text
636    /// declare function add(a: number, b: number): number
637    /// declare config: { name: string, retries: number }
638    /// ```
639    ///
640    /// The definitions are validated before being recorded: if they are
641    /// malformed, this returns [`Error::TypeError`](crate::Error::TypeError)
642    /// carrying the (`in_definitions`) diagnostics and records nothing. On
643    /// success they are appended to this VM's accumulated definitions.
644    pub fn add_definitions(&self, defs: &str) -> Result<()> {
645        // Validate the new definitions in isolation by checking a trivial body.
646        if let Err(diagnostics) = crate::typecheck::check_with_definitions("return nil", defs) {
647            // Only the definition-side diagnostics are this call's fault; a
648            // type error in the trivial body would be ours, not the caller's.
649            let def_errors: Vec<crate::TypeDiagnostic> = diagnostics
650                .into_iter()
651                .filter(|d| d.in_definitions)
652                .collect();
653            if !def_errors.is_empty() {
654                return Err(Error::TypeError(def_errors));
655            }
656        }
657        // Append, newline-separated, to the accumulated definitions.
658        let mut store = self.inner.typecheck_defs.borrow_mut();
659        if !store.is_empty() {
660            store.push('\n');
661        }
662        store.push_str(defs);
663        Ok(())
664    }
665
666    /// Type-check `source` against this VM's accumulated host definitions.
667    ///
668    /// Returns `Ok(())` if the source type-checks clean, or
669    /// [`Error::TypeError`](crate::Error::TypeError) carrying the structured
670    /// diagnostics otherwise.
671    ///
672    /// The Luau VM is dynamically typed, so this is **advisory**: a script that
673    /// fails the check can still be run (`exec`/`eval`). The value is catching
674    /// host-API misuse statically, before running untrusted or generated code.
675    pub fn check(&self, source: &str) -> Result<()> {
676        let defs = self.inner.typecheck_defs.borrow();
677        let result = if defs.is_empty() {
678            crate::typecheck::check(source)
679        } else {
680            crate::typecheck::check_with_definitions(source, &defs)
681        };
682        result.map_err(Error::TypeError)
683    }
684
685    /// Type-check `source` against this VM's accumulated host definitions **plus**
686    /// the extra `defs` (for a one-off check that does not persist `defs`).
687    ///
688    /// Same mapping as [`Lua::check`]: `Ok(())` when clean, otherwise
689    /// [`Error::TypeError`](crate::Error::TypeError).
690    pub fn check_with_definitions(&self, source: &str, defs: &str) -> Result<()> {
691        let accumulated = self.inner.typecheck_defs.borrow();
692        let combined = if accumulated.is_empty() {
693            defs.to_string()
694        } else {
695            format!("{accumulated}\n{defs}")
696        };
697        crate::typecheck::check_with_definitions(source, &combined).map_err(Error::TypeError)
698    }
699}
700
701/// An owned registry reference to a Lua value.
702///
703/// Keeps both the value reachable (registry slot) and the VM alive (the cloned
704/// `XRc<LuaInner>`). On drop it releases the slot via [`lua_unref`].
705pub(crate) struct LuaRef {
706    inner: XRc<LuaInner>,
707    id: Cell<c_int>,
708}
709
710// `LuaRef` is shared behind `XRc<LuaRef>` (`Arc<LuaRef>` under the feature) by
711// every handle, so it must be `Send + Sync` for the handles to be `Send`. The
712// `Cell<c_int>` slot is only ever mutated on the owning thread (the move-only
713// contract); marking `LuaRef` `Sync` is sound under that contract. Handles stay
714// `!Sync` via their own `NotSync` markers.
715#[cfg(feature = "send")]
716unsafe impl Send for LuaRef {}
717#[cfg(feature = "send")]
718unsafe impl Sync for LuaRef {}
719
720impl LuaRef {
721    /// The owning [`Lua`] handle (a fresh borrow sharing the same inner state).
722    pub(crate) fn lua(&self) -> Lua {
723        Lua {
724            inner: self.inner.clone(),
725            _not_sync: NOT_SYNC,
726        }
727    }
728
729    /// The raw state pointer this ref belongs to.
730    #[inline]
731    pub(crate) fn state(&self) -> *mut lua_State {
732        self.inner.state
733    }
734
735    /// The registry id. (Retained for internal diagnostics; handle identity is
736    /// established via `lua_topointer`, not the registry slot id.)
737    #[inline]
738    #[allow(dead_code)]
739    pub(crate) fn id(&self) -> c_int {
740        self.id.get()
741    }
742
743    /// Push the referenced value back onto the stack.
744    pub(crate) fn push(&self) {
745        // The registry table lives at LUA_REGISTRYINDEX; `lua_ref` stores
746        // values keyed by their integer id, so a `rawgeti` on the registry
747        // recovers them. luaur exposes this through getfield on the registry
748        // via the same mechanism `lua_getref` uses in upstream Luau:
749        // `lua_rawgeti(L, LUA_REGISTRYINDEX, id)`.
750        unsafe {
751            luaur_vm::functions::lua_rawgeti::lua_rawgeti(
752                self.state(),
753                luaur_vm::macros::lua_registryindex::LUA_REGISTRYINDEX,
754                self.id.get(),
755            );
756        }
757    }
758}
759
760impl Clone for LuaRef {
761    fn clone(&self) -> Self {
762        // Re-push the value and take a fresh registry slot, so each clone owns
763        // an independent slot (simplest correct behavior).
764        self.push();
765        let new = self.lua().pop_ref();
766        new
767    }
768}
769
770impl Drop for LuaRef {
771    fn drop(&mut self) {
772        let id = self.id.get();
773        // Only unref live, real slots.
774        if id > 0 && !self.inner.state.is_null() {
775            unsafe { lua_unref(self.inner.state, id) };
776        }
777    }
778}
779
780impl Lua {
781    /// Convenience: convert a top-of-stack value (at `idx`) into a [`Value`],
782    /// taking a registry ref for reference types. Does not pop.
783    pub(crate) fn value_from_stack(&self, idx: c_int) -> Result<Value> {
784        crate::value::value_from_stack(self, idx)
785    }
786
787    /// Push a [`Value`] onto the stack.
788    pub(crate) fn push_value(&self, value: &Value) -> Result<()> {
789        crate::value::push_value(self, value)
790    }
791
792    /// Metatable-aware `tostring` of a [`Value`] (honors `__tostring`),
793    /// mirroring Lua's `tostring`/`luaL_tolstring`.
794    pub(crate) fn value_to_string(&self, value: &Value) -> Result<String> {
795        let state = self.state();
796        unsafe {
797            self.push_value(value)?;
798            let mut len = 0usize;
799            let p = lua_l_tolstring(state, -1, &mut len);
800            let out = if p.is_null() {
801                String::new()
802            } else {
803                let bytes = core::slice::from_raw_parts(p as *const u8, len);
804                String::from_utf8_lossy(bytes).into_owned()
805            };
806            // luaL_tolstring pushes the result string; pop it plus the value.
807            lua_pop(state, 2);
808            Ok(out)
809        }
810    }
811
812    /// Map a `lua_pcall`/`luau_load` status code plus the error object on the
813    /// stack into an [`Error`]. Assumes a non-zero status and that the error
814    /// object is on top of the stack; pops it.
815    pub(crate) fn pop_error(&self, status: c_int) -> Error {
816        let state = self.state();
817        unsafe {
818            // First, see if the error object is one of our *structured* error
819            // userdata (raised for scope-destruction errors). If so, recover the
820            // original `Error` and wrap it in `CallbackError`, mirroring mlua.
821            if let Some(cause) = crate::callback::recover_wrapped_error(state, -1) {
822                lua_pop(state, 1);
823                return Error::CallbackError {
824                    traceback: String::new(),
825                    cause: std::sync::Arc::new(cause),
826                };
827            }
828            // Otherwise, fall back to the flat string error path.
829            let mut len = 0usize;
830            let s = lua_tolstring(state, -1, &mut len);
831            let msg = if s.is_null() {
832                "<non-string error>".to_string()
833            } else {
834                let bytes = core::slice::from_raw_parts(s as *const u8, len);
835                String::from_utf8_lossy(bytes).into_owned()
836            };
837            lua_pop(state, 1);
838            // `LUA_ERRMEM` (status 4) is an out-of-memory error (the VM set the
839            // error object to "not enough memory"); surface it as `MemoryError`
840            // so `set_memory_limit` callers can match it, mirroring mlua.
841            // `luau_load` reports OOM with a generic non-zero rc but the same
842            // "not enough memory" message, so we also detect it by message.
843            if status == 4 || msg == "not enough memory" {
844                return Error::MemoryError(msg);
845            }
846            Error::RuntimeError(msg)
847        }
848    }
849}