Skip to main content

mlua_isle/
runtime.rs

1//! Running Lua on a VM you own: the in-thread layer of the crate.
2//!
3//! The crate has two layers.  The actors ([`Isle`](crate::Isle),
4//! `AsyncIsle`, the pools) put a VM on a thread of their own and take
5//! requests over channels.  This module is the layer underneath: a host
6//! that owns the [`Lua`] and drives the executor itself (its own thread
7//! and [`LocalSet`](https://docs.rs/tokio/latest/tokio/task/struct.LocalSet.html))
8//! uses it directly, and the actors are built on it.
9//!
10//! [`Vm`] is the entry point: [`Vm::attach`] takes over the VM's debug
11//! hook, stores its [`Config`] and creates the `task` library.  The
12//! hook part (`attach`, `of`, `config`, `set_config`, `add_hook`,
13//! `remove_hook`) is always available; `Vm::run`, `Vm::task_lib`,
14//! `cancellable` and `current_scope` need the `tokio` feature.  With
15//! it, setup is three calls (see `Vm::run` for the full example):
16//!
17//! ```text
18//! let vm = Vm::attach(&lua, Config { grace: Duration::from_secs(1), ..Default::default() })?;
19//! lua.globals().set("task", vm.task_lib()?)?;
20//! let out = local.run_until(vm.run(&token, main, ())).await?;
21//! ```
22//!
23//! # Contracts
24//!
25//! 1. **When `run` resolves, nothing the root started is alive.**  This
26//!    holds for Lua tasks (`task.spawn`) and for host tasks spawned
27//!    through the scope (`current_scope()` then
28//!    `ScopeHandle::spawn_local`), transitively and in any mix,
29//!    whether the root finished or was cancelled.  A host task that
30//!    ignores its token is dropped when the grace ends.  Tasks spawned
31//!    into a scope that is already ending share its remaining time; a
32//!    spawn after the remaining time is gone starts nothing.  The layer
33//!    does not drain the host's `LocalSet`: a `spawn_local` that bypasses the
34//!    scope (for example `current_token().child_token()` plus a bare
35//!    `tokio::task::spawn_local`) is cancelled with the request but is
36//!    neither waited for nor dropped, and is the host's
37//!    responsibility.  This holds when `run` is awaited to the end:
38//!    dropping the `run` future instead only schedules the tasks for
39//!    abort, and a task in a CPU loop blocks `run` until it yields,
40//!    which without [`Config::preempt_every`] it never does.
41//! 2. **One error type**, [`IsleError`], on this layer and on the
42//!    actors, with one payload for a Lua error: [`IsleError::Lua`]
43//!    carries a [`LuaFailure`] (kind, message as Lua prints it,
44//!    traceback, and with the `serde` feature the raised value as
45//!    JSON), built on the VM thread from the raised value, the same
46//!    for `run` and for every actor request.  A cancel is
47//!    [`IsleError::Cancelled`], recognised by value: the cancel error
48//!    is `mlua::Error::external(`[`Cancelled`]`)`, found by downcast,
49//!    never by message.
50//! 3. **The layer owns the VM's debug hook.**  Register callbacks with
51//!    [`Vm::add_hook`], never with `Lua::set_hook` /
52//!    `Lua::set_global_hook`, which replace the hook and stop
53//!    cancellation (see [Hooks](#hooks)).
54//! 4. **One [`Config`] per VM**, read and written through [`Vm`]
55//!    ([`Vm::config`], [`Vm::set_config`]; a second [`Vm::attach`]
56//!    replaces it).
57//! 5. **Cancellation is a token the host creates** and passes to
58//!    `run`; `run` spawns nothing and returns no handle.  Ctrl-C, a
59//!    timeout or a hook callback cancel that [`CancelToken`].
60//!
61//! Two requirements on the VM itself: attach it before sandboxing its
62//! globals (the first [`Vm::attach`] captures `xpcall`), and keep mlua's
63//! default `LuaOptions::catch_rust_panics = true`, whose `xpcall` is
64//! yieldable (with `false` every yield in a `run` root fails; see
65//! [`Vm::attach`]).
66//!
67//! Host functions called from Lua reach the running request or task
68//! through the context functions, which read a thread-local and so take
69//! no receiver: [`current_token`], `cancellable` and `current_scope`.
70//!
71//! # Hooks
72//!
73//! Lua has one hook slot per thread, and mlua's hook setters replace
74//! whatever was there, so the layer owns the VM's hook: [`Vm::attach`]
75//! installs a single **global** hook (one callback shared by every
76//! thread of the VM, including coroutines the Lua code creates) that,
77//! in order,
78//!
79//! 1. raises the cancellation error ([`Cancelled`]) when the token of
80//!    the request or task currently executing is cancelled (checked
81//!    every 1000 instructions),
82//! 2. calls the callbacks registered with [`Vm::add_hook`], each at its
83//!    own [`HookTriggers`],
84//! 3. yields the running root coroutine or task every N checks when
85//!    preemption is enabled ([`Config::preempt_every`]).
86//!
87//! Calling [`Lua::set_hook`], [`Lua::set_global_hook`] or
88//! [`mlua::Thread::set_hook`] on the VM replaces this hook, and
89//! cancellation stops working.  The hook is re-installed when a
90//! `set_hook` replacement is noticed (at the start of every actor
91//! request and of every `Vm::run`), but a replacement through
92//! `set_global_hook` cannot be detected.
93//!
94//! # The `task` library
95//!
96//! `Vm::task_lib` (`tokio` feature) returns the VM's `task` table,
97//! conventionally set as the global `task`:
98//!
99//! | Lua | meaning |
100//! |---|---|
101//! | `task.spawn(f, ...)` | Start `f(...)` as a concurrent task of the current coroutine request or task.  Returns a handle. |
102//! | `h:join()` | Wait for the task.  Returns `true, ...` (what `f` returned) or `false, err`, where `err` is the raw Lua error value, or `task.CANCELLED` if the task was cancelled.  A handle can be joined once. |
103//! | `h:cancel()` | Request cancellation.  Does not wait. |
104//! | `h:done()` | Whether the task has finished. |
105//! | `local h <close> = task.spawn(...)` | On scope exit, a task that was not joined is cancelled and waited for. |
106//! | `task.is_cancelled(err)` | Whether `err` is a cancellation: the error a cancel raises (caught with `pcall`, or received by a `__close` handler) or `task.CANCELLED`.  `false` for any other value. |
107//! | `task.CANCELLED` | What `join` returns as `err` for a cancelled task. |
108//!
109//! Tasks are **structured**: when a coroutine request or task finishes,
110//! the tasks it spawned and did not join are cancelled, and it waits
111//! for them before its own result is delivered.  Cancelling a request
112//! or task cancels all of its tasks (their tokens are children of its
113//! token, see [`CancelToken::child_token`]), and the cancelled request
114//! or task still resolves only after they, and their own tasks, have
115//! finished or been dropped.  The [grace](Config::grace) is one deadline
116//! for the whole tree: a task spawned during cleanup gets the time that
117//! remains, not a fresh grace period.
118//!
119//! `task.spawn` works inside `Vm::run`, inside coroutine requests
120//! (`AsyncIsle::coroutine_eval` / `coroutine_call`) and inside tasks
121//! (including host tasks).  Sync requests (`eval` / `call` / `exec`)
122//! cannot await, so `task.spawn` raises an error there.
123//!
124//! A cancel reaches Lua code as an error: the cancel hook raises it
125//! while Lua code runs, and an async host function wrapped with
126//! `cancellable` returns it while the coroutine awaits.  Its value is
127//! `mlua::Error::external(`[`Cancelled`]`)` (a userdata to Lua);
128//! `task.is_cancelled(err)` is the test, and it is also true for
129//! `task.CANCELLED`, so one predicate covers both:
130//!
131//! ```lua
132//! local ok, err = pcall(sleep, 1000)
133//! if not ok and task.is_cancelled(err) then
134//!   -- cancelled: clean up and let the cancel continue
135//!   error(err, 0)
136//! end
137//! ```
138//!
139//! The predicate lives in the library: a VM that runs without the `task`
140//! table has no `task.is_cancelled`; Rust code tests an `mlua::Error`
141//! with `e.downcast_ref::<Cancelled>()`.
142//!
143//! A task that runs a CPU loop never yields on its own, so a sibling on
144//! the same thread cannot run to cancel it; enable
145//! [`Config::preempt_every`] for that.  Cancelling from another thread
146//! (an `AsyncTask` handle) works without it.
147//!
148//! # Host tasks
149//!
150//! A host function that starts work of its own takes the scope of the
151//! running request or task with `current_scope()` and spawns into it
152//! with `ScopeHandle::spawn_local`.  Such a task is structured like a
153//! Lua task: it is cancelled when the request or task ends or is
154//! cancelled, gets the grace (one deadline for the whole tree), is
155//! dropped when the grace ends, and is waited for.  Take the handle in
156//! the synchronous part of the host function (the `create_function`
157//! body, or a `create_async_function` body before its first `.await`)
158//! and move it into the future; `current_scope()` is `Some` only while
159//! a coroutine request or task is being polled, so it is `None` in a
160//! sync request.  `spawn_local` returns a `ScopedTask`; there are three
161//! ways to let go of it: await it (wait for the value), keep it for as
162//! long as the task should run (dropping it cancels the task now), or
163//! `detach()` it (fire and forget: the task runs on without a handle and
164//! is still cancelled, given the grace, dropped and waited for when the
165//! scope ends).
166//!
167//! ```text
168//! let bg = lua.create_function(|_, ()| {
169//!     let scope = current_scope().expect("inside a coroutine request");
170//!     scope.spawn_local(async move { /* host work */ }).detach();
171//!     Ok(())
172//! })?;
173//! ```
174
175use crate::hub;
176use mlua::debug::Debug;
177use mlua::{HookTriggers, Lua, VmState};
178use std::cell::RefCell;
179use std::fmt;
180use std::time::Duration;
181
182pub use crate::error::{Cancelled, IsleError, LuaErrorKind, LuaFailure};
183pub use crate::hook::{current_token, CancelToken};
184#[cfg(feature = "tokio")]
185pub use crate::scope::{cancellable, current_scope, ScopeHandle, ScopedTask};
186
187/// Settings of a VM.  One per VM, read and written through [`Vm`]
188/// ([`Vm::attach`], [`Vm::config`], [`Vm::set_config`]).
189#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
190pub struct Config {
191    /// How long a cancelled coroutine request or task may keep running
192    /// to finish its cleanup before it is dropped.
193    ///
194    /// On cancel, the coroutine first receives the cancellation as a Lua
195    /// error (from the cancel hook while it runs, or from an async
196    /// function wrapped with `cancellable` while it awaits).  That error
197    /// unwinds normally, so `__close` handlers run and may await.  If
198    /// the coroutine has not finished when the grace period ends, it is
199    /// dropped: the awaited Rust future is released, and pending
200    /// `__close` handlers run without being able to yield (a Lua 5.4
201    /// restriction).
202    ///
203    /// The grace period is one deadline for the cancelled request or
204    /// task and every task it spawned, transitively: a task started
205    /// during cleanup (from a `__close` handler, say) gets the time that
206    /// remains, not a fresh grace period.
207    ///
208    /// Default: zero (drop at once).
209    pub grace: Duration,
210    /// Yield the running coroutine request or task every this many
211    /// cancel checks (a check runs every 1000 instructions), so that
212    /// other tasks on the same thread, including one that cancels it,
213    /// get to run while it is in a CPU loop.
214    ///
215    /// Only the coroutine that the crate created for the request or task
216    /// is yielded, never a coroutine the Lua code created itself (that
217    /// yield would reach the Lua code's own `coroutine.resume` as a
218    /// spurious yield).  Code in a non-yieldable context (a metamethod,
219    /// a C function boundary) is not yielded.
220    ///
221    /// Yielding lets other tasks interleave at points the Lua code did
222    /// not mark, so Lua code that updates shared state across such a
223    /// point can observe changes made by another task.
224    ///
225    /// Default: `None` (never preempt).
226    pub preempt_every: Option<u32>,
227}
228
229/// Handle of a callback registered with [`Vm::add_hook`].
230#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
231pub struct HookId(pub(crate) u64);
232
233/// Marks a VM as attached; holds the per-VM state that is not in the
234/// hook hub.
235#[derive(Default)]
236struct Attached {
237    /// The `task` table, created on the first [`Vm::task_lib`] call, so
238    /// that a VM that never asks for it (an actor whose init closure
239    /// does not) runs no extra Lua.  Kept in the registry, not as a
240    /// global.
241    #[cfg(feature = "tokio")]
242    task: std::cell::OnceCell<mlua::RegistryKey>,
243}
244
245/// The in-thread handle of a Lua VM run by this crate.
246///
247/// A `Vm` is a clone of the [`Lua`] handle; its state lives in the VM,
248/// so every `Vm` of the same VM (from [`Vm::attach`] or [`Vm::of`]) sees
249/// the same state.  It holds the VM strongly: do not store it in
250/// something the VM owns (a Lua function's captured state, app data),
251/// or the VM is never freed.
252#[derive(Clone)]
253pub struct Vm {
254    lua: Lua,
255}
256
257impl fmt::Debug for Vm {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.debug_struct("Vm")
260            .field("config", &self.config())
261            .finish_non_exhaustive()
262    }
263}
264
265impl Vm {
266    /// Install the hook and store `config`.
267    ///
268    /// Calling it again on the same VM re-installs the hook, replaces
269    /// the config (last wins) and returns a `Vm` for the same state; the
270    /// task table, if `Vm::task_lib` created it, is kept.  Runs no Lua
271    /// code.
272    ///
273    /// Hook callbacks registered before (with [`Vm::add_hook`]) are
274    /// kept.
275    ///
276    /// The first `attach` also captures the `xpcall` global, which
277    /// [`Vm::run`] uses to bring a raised Lua value back as a value (see
278    /// [`LuaFailure`]).  **Attach before sandboxing the globals**
279    /// (removing `xpcall`, or [`Lua::set_globals`] with a whitelist):
280    /// after that the capture is kept, and later changes to the globals
281    /// or a re-attach do not affect it.
282    ///
283    /// **The coroutine path needs mlua's default
284    /// `LuaOptions::catch_rust_panics = true`.**  With `false`, mlua
285    /// replaces the global `xpcall` with a version that is not
286    /// yieldable, so every yield in a root run by [`Vm::run`] (an async
287    /// host function, `task.join`, preemption) fails with "attempt to
288    /// yield across a C-call boundary".  [`Lua::new`] uses the default.
289    ///
290    /// # Errors
291    ///
292    /// [`IsleError::Init`] with [`LuaErrorKind::External`] when the VM's
293    /// `xpcall` global is not a function (it was sandboxed away before
294    /// the first attach).
295    pub fn attach(lua: &Lua, config: Config) -> Result<Vm, IsleError> {
296        crate::protect::install(lua)?;
297        hub::install(lua)?;
298        hub::set_config(lua, config);
299        let attached = lua.app_data_ref::<Attached>().is_some();
300        if !attached {
301            lua.set_app_data(Attached::default());
302        }
303        Ok(Vm { lua: lua.clone() })
304    }
305
306    /// The `Vm` of `lua`, if [`Vm::attach`] was called on it.
307    pub fn of(lua: &Lua) -> Option<Vm> {
308        let attached = lua.app_data_ref::<Attached>().is_some();
309        attached.then(|| Vm { lua: lua.clone() })
310    }
311
312    /// The VM's settings.
313    pub fn config(&self) -> Config {
314        hub::config(&self.lua)
315    }
316
317    /// Replace the VM's settings.  Takes effect for requests and tasks
318    /// that start afterwards (and, for `preempt_every`, at once).
319    pub fn set_config(&self, config: Config) {
320        hub::set_config(&self.lua, config);
321    }
322
323    /// Register a hook callback, run from the VM's hook after the cancel
324    /// check at `triggers` (see [Hooks](self#hooks)).
325    ///
326    /// Instruction counts are approximated to the hook's step (the
327    /// smallest count among all registrations and the cancel check).
328    /// Returning [`VmState::Yield`] yields the running coroutine,
329    /// including a coroutine the Lua code created itself, where the
330    /// yield reaches the Lua code's `coroutine.resume`.
331    ///
332    /// The callback applies to the main thread and to coroutines created
333    /// afterwards; coroutines that already exist keep the instruction
334    /// count and events they were created with.  It is kept across a
335    /// second [`Vm::attach`].
336    ///
337    /// The callback is not re-entered.  A callback that runs Lua code
338    /// can be hooked again from inside itself: resuming a coroutine is
339    /// the usual case, because the new thread has hooks enabled while
340    /// the hooked thread does not.  That inner call fails with
341    /// [`mlua::Error::RecursiveMutCallback`].
342    ///
343    /// Known limit: a request's Lua error goes through the crate's
344    /// message handler (a C function under `xpcall`).  Count and line
345    /// callbacks do not fire inside it, but a callback with `on_calls` /
346    /// `on_returns` fires for the handler's own call and return.  If
347    /// that callback returns `Err`, its error replaces the original Lua
348    /// error (the request fails with "error in error handling" or the
349    /// callback's error).  Do not fail from call / return callbacks if
350    /// the original error matters.
351    pub fn add_hook<F>(&self, triggers: HookTriggers, f: F) -> Result<HookId, IsleError>
352    where
353        F: FnMut(&Lua, &Debug) -> mlua::Result<VmState> + 'static,
354    {
355        let f = RefCell::new(f);
356        hub::add_hook(&self.lua, triggers, move |lua, debug| {
357            let mut f = f
358                .try_borrow_mut()
359                .map_err(|_| mlua::Error::RecursiveMutCallback)?;
360            f(lua, debug)
361        })
362    }
363
364    /// Remove a callback registered with [`Vm::add_hook`].  Returns
365    /// whether it was registered.
366    pub fn remove_hook(&self, id: HookId) -> Result<bool, IsleError> {
367        hub::remove_hook(&self.lua, id)
368    }
369
370    /// The `task` library table (see [The `task` library](self#the-task-library)).
371    ///
372    /// It is not set as a global: the host decides where it lives,
373    /// e.g. `lua.globals().set("task", vm.task_lib()?)`.  The table is
374    /// created on the first call (this runs the library's Lua chunk);
375    /// every later call, through any `Vm` of the same VM, returns the
376    /// same table.
377    ///
378    /// In an actor's init closure the VM is not attached yet: attach it
379    /// there (the actor re-attaches after the closure and keeps the
380    /// config and the table).  `?` converts the [`IsleError`] into the
381    /// closure's `mlua::Error`.
382    ///
383    /// ```rust
384    /// # #[tokio::main]
385    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
386    /// use mlua_isle::runtime::{Config, Vm};
387    /// use mlua_isle::AsyncIsle;
388    ///
389    /// let (isle, driver) = AsyncIsle::spawn(|lua| {
390    ///     let vm = Vm::attach(lua, Config::default())?;
391    ///     lua.globals().set("task", vm.task_lib()?)
392    /// })
393    /// .await?;
394    /// let r: i64 = isle
395    ///     .coroutine_eval(
396    ///         "local h = task.spawn(function(a, b) return a + b end, 1, 2)
397    ///          local ok, sum = h:join()
398    ///          return sum",
399    ///     )
400    ///     .await?;
401    /// assert_eq!(r, 3);
402    /// driver.shutdown().await?;
403    /// # Ok(())
404    /// # }
405    /// ```
406    ///
407    /// # Errors
408    ///
409    /// Fails only when creating the table fails (e.g. the VM's memory
410    /// limit is reached).
411    #[cfg(feature = "tokio")]
412    pub fn task_lib(&self) -> Result<mlua::Table, IsleError> {
413        if let Some(t) = self.cached_task_lib()? {
414            return Ok(t);
415        }
416        // Created without holding the app data borrow: the chunk runs
417        // under the hook, whose callbacks may touch app data.
418        let key = self
419            .lua
420            .create_registry_value(crate::task_lib::create(&self.lua)?)?;
421        {
422            let a = self.attached();
423            // A table stored meanwhile wins; `key` is then dropped.
424            let _ = a.task.set(key);
425        }
426        Ok(self
427            .cached_task_lib()?
428            .expect("the task table was just stored"))
429    }
430
431    #[cfg(feature = "tokio")]
432    fn cached_task_lib(&self) -> Result<Option<mlua::Table>, IsleError> {
433        let a = self.attached();
434        match a.task.get() {
435            Some(key) => Ok(Some(self.lua.registry_value(key)?)),
436            None => Ok(None),
437        }
438    }
439
440    #[cfg(feature = "tokio")]
441    fn attached(&self) -> mlua::AppDataRef<'_, Attached> {
442        self.lua
443            .app_data_ref::<Attached>()
444            .expect("a Vm exists only for an attached VM")
445    }
446
447    /// Run `f(args)` as a root coroutine under `token`.
448    ///
449    /// Resolves only after everything the root started has ended: the
450    /// Lua tasks it spawned and the host tasks spawned through
451    /// [`current_scope`], transitively (contract 1 of the
452    /// [module docs](self)).  Resolves to `Err(IsleError::Cancelled)` if
453    /// `token` was cancelled, whatever the coroutine returned; the
454    /// coroutine and its tasks then get the VM's [`Config::grace`], as
455    /// one deadline, before they are dropped.  The cancellation error
456    /// raised by some other token (a host function that returned
457    /// `Err(mlua::Error::external(Cancelled))`) also resolves to
458    /// `Err(IsleError::Cancelled)`.
459    ///
460    /// A Lua error resolves to `Err(IsleError::Lua(f))`, where the
461    /// [`LuaFailure`] is built from the raised value itself on this
462    /// thread: `f.message` is `tostring(err)` and, with the `serde`
463    /// feature, `f.value` is the value as JSON (so `error({ code = 42 })`
464    /// gives `f.value["code"] == 42`).
465    ///
466    /// A task in a CPU loop cannot be dropped until it yields; without
467    /// [`Config::preempt_every`] the wait blocks on it.
468    ///
469    /// Await it inside a [`tokio::task::LocalSet`].
470    ///
471    /// # Dropping the future
472    ///
473    /// Dropping the returned future before it resolves (wrapping it in
474    /// [`tokio::time::timeout`], or a losing [`tokio::select!`] arm)
475    /// drops the coroutine at once but only schedules the tasks it
476    /// spawned for abort: tokio drops them on a later poll of the
477    /// `LocalSet`, as with
478    /// [`AbortHandle::abort`](tokio::task::AbortHandle::abort).  To have
479    /// the tasks gone before you continue, [cancel](CancelToken::cancel)
480    /// the token and await the future instead of dropping it.
481    ///
482    /// ```rust
483    /// use mlua_isle::runtime::{CancelToken, Config, Vm};
484    /// use std::time::Duration;
485    ///
486    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
487    /// let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
488    /// let local = tokio::task::LocalSet::new();
489    /// let lua = mlua::Lua::new();
490    ///
491    /// let vm = Vm::attach(&lua, Config { grace: Duration::from_secs(1), ..Default::default() })?;
492    /// lua.globals().set("task", vm.task_lib()?)?;
493    /// let main: mlua::Function = lua
494    ///     .load("return function(x) local _, v = task.spawn(function() return x * 2 end):join() return v end")
495    ///     .eval()?;
496    ///
497    /// let token = CancelToken::new();
498    /// let out = local.block_on(&rt, vm.run(&token, main, 21))?;
499    /// assert_eq!(out[0].as_i64(), Some(42));
500    /// # Ok(())
501    /// # }
502    /// ```
503    #[cfg(feature = "tokio")]
504    pub async fn run(
505        &self,
506        token: &CancelToken,
507        f: mlua::Function,
508        args: impl mlua::IntoLuaMulti,
509    ) -> Result<mlua::MultiValue, IsleError> {
510        let args = args.into_lua_multi(&self.lua)?;
511        crate::scope::run_root(&self.lua, token.clone(), f, args).await
512    }
513}
514
515/// Attach an actor's VM after its init closure ran.
516///
517/// With `config`, it replaces whatever the init closure configured;
518/// without, the VM keeps the init closure's settings (the default if it
519/// set none).  The hook is (re-)installed either way, so a hook the init
520/// closure set with `Lua::set_hook` is replaced, as before.
521pub(crate) fn attach_after_init(lua: &Lua, config: Option<Config>) -> Result<Vm, IsleError> {
522    let config = config.unwrap_or_else(|| hub::config(lua));
523    Vm::attach(lua, config)
524}
525
526/// Make sure the VM is attached and its hook is in place, before a
527/// request runs.  Re-installs the hook if `Lua::set_hook` replaced it;
528/// keeps the stored config.
529pub(crate) fn ensure_attached(lua: &Lua) -> Result<(), IsleError> {
530    let attached = lua.app_data_ref::<Attached>().is_some();
531    if attached {
532        hub::ensure_installed(lua)
533    } else {
534        // Unreachable for the actors (they attach before reporting a
535        // successful spawn); kept as a defensive path.
536        attach_after_init(lua, None).map(drop)
537    }
538}
539
540/// The [`Vm`] of `lua`, attaching it with its stored config (the
541/// default if none was set) when it is not attached yet.
542pub(crate) fn of_or_attach(lua: &Lua) -> Result<Vm, IsleError> {
543    match Vm::of(lua) {
544        Some(vm) => Ok(vm),
545        None => attach_after_init(lua, None),
546    }
547}