mlua_isle/lib.rs
1//! Thread-isolated Lua VM with cancellation for mlua.
2//!
3//! `mlua-isle` runs a Lua VM on a dedicated thread and communicates via
4//! channels. This solves two fundamental problems with mlua:
5//!
6//! 1. **`Lua` is `!Send`** — it cannot cross thread boundaries. By
7//! confining the VM to one thread and sending requests over a channel,
8//! callers on any thread (UI, async runtime, etc.) can interact with
9//! Lua without `Send` issues.
10//!
11//! 2. **Cancellation** — long-running Lua code (including blocking Rust
12//! callbacks like HTTP calls) can be interrupted via a cancel token
13//! that triggers both a Lua debug hook and a caller-side signal.
14//!
15//! # Architecture
16//!
17//! ```text
18//! ┌─────────────────┐ mpsc ┌──────────────────┐
19//! │ caller thread │─────────►│ Lua thread │
20//! │ (UI / async) │ │ (mlua confined) │
21//! │ │◄─────────│ │
22//! │ Isle handle │ oneshot │ Lua VM + hook │
23//! └─────────────────┘ └──────────────────┘
24//! ```
25//!
26//! # Example
27//!
28//! ```rust
29//! use mlua_isle::Isle;
30//!
31//! let isle = Isle::spawn(|lua| {
32//! lua.globals().set("greeting", "hello")?;
33//! Ok(())
34//! }).unwrap();
35//!
36//! let result: String = isle.eval("return greeting").unwrap();
37//! assert_eq!(result, "hello");
38//!
39//! isle.shutdown().unwrap();
40//! ```
41
42mod error;
43mod handle;
44mod hook;
45mod task;
46mod thread;
47
48pub use error::IsleError;
49pub use handle::Isle;
50pub use hook::CancelToken;
51pub use task::Task;
52
53/// Type alias for exec closures to keep the `Request` enum readable.
54pub(crate) type ExecFn = Box<dyn FnOnce(&mlua::Lua) -> Result<String, IsleError> + Send>;
55
56/// Channel sender for results.
57pub(crate) type ResultTx = std::sync::mpsc::Sender<Result<String, IsleError>>;
58
59/// Request sent from caller to the Lua thread.
60pub(crate) enum Request {
61 /// Evaluate a Lua chunk and return the result as a string.
62 Eval {
63 code: String,
64 cancel: CancelToken,
65 tx: ResultTx,
66 },
67 /// Call a named global function with string arguments.
68 Call {
69 func: String,
70 args: Vec<String>,
71 cancel: CancelToken,
72 tx: ResultTx,
73 },
74 /// Execute an arbitrary closure on the Lua thread.
75 Exec {
76 f: ExecFn,
77 cancel: CancelToken,
78 tx: ResultTx,
79 },
80 /// Graceful shutdown.
81 Shutdown,
82}