mlua 0.12.3

High level bindings to Lua 5.5/5.4/5.3/5.2/5.1 (including LuaJIT) and Luau with async/await features and support of writing native Lua modules in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
#![cfg(feature = "luau")]

use std::fmt::Debug;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use mlua::chunk::Compiler;
use mlua::{
    Error, Function, InterruptHandle, Lua, LuaOptions, Result, StdLib, Table, Value, Vector, VmState, ffi,
};

#[test]
fn test_version() -> Result<()> {
    let lua = Lua::new();
    assert!(lua.globals().get::<String>("_VERSION")?.starts_with("Luau 0."));
    Ok(())
}

#[cfg(not(feature = "luau-vector4"))]
#[test]
fn test_vectors() -> Result<()> {
    let lua = Lua::new();

    let v: Value = lua
        .load("vector.create(1, 2, 3) + vector.create(3, 2, 1)")
        .eval()?;
    assert!(v.is_vector());
    assert_eq!(v.as_vector().unwrap(), [4.0, 4.0, 4.0]);

    // Test conversion into Rust array
    let v: [f64; 3] = lua.load("vector.create(1, 2, 3)").eval()?;
    assert!(v == [1.0, 2.0, 3.0]);

    // Test vector methods
    lua.load(
        r#"
        local v = vector.create(1, 2, 3)
        assert(v.x == 1)
        assert(v.y == 2)
        assert(v.z == 3)
    "#,
    )
    .exec()?;

    // Test vector methods (fastcall)
    lua.load(
        r#"
        local v = vector.create(1, 2, 3)
        assert(v.x == 1)
        assert(v.y == 2)
        assert(v.z == 3)
    "#,
    )
    .set_compiler(Compiler::new().set_vector_ctor("vector"))
    .exec()?;

    Ok(())
}

#[cfg(feature = "luau-vector4")]
#[test]
fn test_vectors() -> Result<()> {
    let lua = Lua::new();

    let v: Value = lua
        .load("vector.create(1, 2, 3, 4) + vector.create(4, 3, 2, 1)")
        .eval()?;
    assert!(v.is_vector());
    assert_eq!(v.as_vector().unwrap(), [5.0, 5.0, 5.0, 5.0]);

    // Test conversion into Rust array
    let v: [f64; 4] = lua.load("vector.create(1, 2, 3, 4)").eval()?;
    assert!(v == [1.0, 2.0, 3.0, 4.0]);

    // Test vector methods
    lua.load(
        r#"
        local v = vector.create(1, 2, 3, 4)
        assert(v.x == 1)
        assert(v.y == 2)
        assert(v.z == 3)
        assert(v.w == 4)
    "#,
    )
    .exec()?;

    // Test vector methods (fastcall)
    lua.load(
        r#"
        local v = vector.create(1, 2, 3, 4)
        assert(v.x == 1)
        assert(v.y == 2)
        assert(v.z == 3)
        assert(v.w == 4)
    "#,
    )
    .set_compiler(Compiler::new().set_vector_ctor("vector"))
    .exec()?;

    Ok(())
}

#[test]
fn test_vector_metatable() -> Result<()> {
    let lua = Lua::new();

    let vector_mt = lua
        .load(
            r#"
            {
                __index = {
                    new = vector.create,

                    product = function(a, b)
                        return vector.create(a.x * b.x, a.y * b.y, a.z * b.z)
                    end
                }
            }
    "#,
        )
        .eval::<Table>()?;
    vector_mt.set_metatable(Some(vector_mt.clone()))?;
    lua.set_type_metatable::<Vector>(Some(vector_mt.clone()));
    lua.globals().set("Vector3", vector_mt)?;

    let compiler = Compiler::new()
        .set_vector_ctor("Vector3.new")
        .set_vector_type("Vector3");

    // Test vector methods (fastcall)
    lua.load(
        r#"
        local v = Vector3.new(1, 2, 3)
        local v2 = v:product(Vector3.new(2, 3, 4))
        assert(v2.x == 2 and v2.y == 6 and v2.z == 12)
    "#,
    )
    .set_compiler(compiler)
    .exec()?;

    Ok(())
}

#[test]
fn test_readonly_table() -> Result<()> {
    let lua = Lua::new();

    let t = lua.create_sequence_from([1])?;
    assert!(!t.is_readonly());
    t.set_readonly(true);
    assert!(t.is_readonly());

    #[track_caller]
    fn check_readonly_error<T: Debug>(res: Result<T>) {
        match res {
            Err(Error::RuntimeError(e)) if e.contains("attempt to modify a readonly table") => {}
            r => panic!("expected RuntimeError(...) with a specific message, got {r:?}"),
        }
    }

    check_readonly_error(t.set("key", "value"));
    check_readonly_error(t.raw_set("key", "value"));
    check_readonly_error(t.raw_insert(1, "value"));
    check_readonly_error(t.raw_remove(1));
    check_readonly_error(t.push("value"));
    check_readonly_error(t.pop::<Value>());
    check_readonly_error(t.raw_push("value"));
    check_readonly_error(t.raw_pop::<Value>());

    // Special case
    match t.set_metatable(None) {
        Err(Error::RuntimeError(e)) if e.contains("attempt to modify a readonly table") => {}
        r => panic!("expected RuntimeError(...) with a specific message, got {r:?}"),
    }

    Ok(())
}

#[test]
fn test_sandbox() -> Result<()> {
    let lua = Lua::new();

    lua.sandbox(true)?;

    lua.load("global = 123").exec()?;
    let n: i32 = lua.load("return global").eval()?;
    assert_eq!(n, 123);
    assert_eq!(lua.globals().get::<Option<i32>>("global")?, Some(123));

    // Threads should inherit "main" globals
    let f = lua.create_function(|lua, ()| lua.globals().get::<i32>("global"))?;
    let co = lua.create_thread(f.clone())?;
    assert_eq!(co.resume::<Option<i32>>(())?, Some(123));

    // Sandboxed threads should also inherit "main" globals
    let co = lua.create_thread(f)?;
    co.sandbox()?;
    assert_eq!(co.resume::<Option<i32>>(())?, Some(123));

    // collectgarbage should be restricted in sandboxed mode
    let collectgarbage = lua.globals().get::<Function>("collectgarbage")?;
    for arg in ["collect", "stop", "restart", "step", "isrunning"] {
        let err = collectgarbage.call::<()>(arg).err().unwrap().to_string();
        assert!(err.contains("collectgarbage called with invalid option"));
    }
    assert!(collectgarbage.call::<f64>("count").unwrap() > 0.0);

    lua.sandbox(false)?;

    // Previously set variable `global` should be cleared now
    assert_eq!(lua.globals().get::<Option<i32>>("global")?, None);

    // Readonly flags should be cleared as well
    let table = lua.globals().get::<Table>("table")?;
    table.set("test", "test")?;

    // collectgarbage should work now
    for arg in ["collect", "stop", "restart", "count", "step", "isrunning"] {
        collectgarbage.call::<()>(arg).unwrap();
    }

    Ok(())
}

#[test]
fn test_sandbox_safeenv() -> Result<()> {
    let lua = Lua::new();

    lua.sandbox(true)?;
    lua.globals().set("state", lua.create_table()?)?;
    lua.globals().set_safeenv(false);
    lua.load("state.a = 123").exec()?;
    let a: i32 = lua.load("state.a = 321; return state.a").eval()?;
    assert_eq!(a, 321);

    Ok(())
}

#[test]
fn test_sandbox_nolibs() -> Result<()> {
    let lua = Lua::new_with(StdLib::NONE, LuaOptions::default()).unwrap();

    lua.sandbox(true)?;
    lua.load("global = 123").exec()?;
    let n: i32 = lua.load("return global").eval()?;
    assert_eq!(n, 123);
    assert_eq!(lua.globals().get::<Option<i32>>("global")?, Some(123));

    lua.sandbox(false)?;
    assert_eq!(lua.globals().get::<Option<i32>>("global")?, None);

    Ok(())
}

#[test]
fn test_sandbox_threads() -> Result<()> {
    let lua = Lua::new();

    let f = lua.create_function(|lua, v: Value| lua.globals().set("global", v))?;

    let co = lua.create_thread(f.clone())?;
    co.resume::<()>(321)?;
    // The main state should see the `global` variable (as the thread is not sandboxed)
    assert_eq!(lua.globals().get::<Option<i32>>("global")?, Some(321));

    let co = lua.create_thread(f.clone())?;
    co.sandbox()?;
    co.resume::<()>(123)?;
    // The main state should see the previous `global` value (as the thread is sandboxed)
    assert_eq!(lua.globals().get::<Option<i32>>("global")?, Some(321));

    // Try to reset the (sandboxed) thread
    co.reset(f)?;
    co.resume::<()>(111)?;
    assert_eq!(lua.globals().get::<Option<i32>>("global")?, Some(111));

    Ok(())
}

#[test]
fn test_interrupts() -> Result<()> {
    let lua = Lua::new();

    let interrupts_count = Arc::new(AtomicU64::new(0));
    let interrupts_count2 = interrupts_count.clone();

    lua.set_interrupt(move |_| {
        interrupts_count2.fetch_add(1, Ordering::Relaxed);
        Ok(VmState::Continue)
    });
    let f = lua
        .load(
            r#"
        local x = 2 + 3
        local y = x * 63
        local z = string.len(x..", "..y)
    "#,
        )
        .into_function()?;
    f.call::<()>(())?;

    assert!(interrupts_count.load(Ordering::Relaxed) > 0);

    //
    // Test yields from interrupt
    //
    let yield_count = Arc::new(AtomicU64::new(0));
    let yield_count2 = yield_count.clone();
    lua.set_interrupt(move |_| {
        if yield_count2.fetch_add(1, Ordering::Relaxed) == 1 {
            return Ok(VmState::Yield);
        }
        Ok(VmState::Continue)
    });
    let co = lua.create_thread(
        lua.load(
            r#"
            local a = {1, 2, 3}
            local b = 0
            for _, x in ipairs(a) do b += x end
            return b
        "#,
        )
        .into_function()?,
    )?;
    co.resume::<()>(())?;
    assert!(co.is_resumable());
    let result: i32 = co.resume(())?;
    assert_eq!(result, 6);
    assert_eq!(yield_count.load(Ordering::Relaxed), 7);
    assert!(co.is_finished());

    // Test no yielding at non-yieldable points
    yield_count.store(0, Ordering::Relaxed);
    let co = lua.create_thread(lua.create_function(|lua, arg: Value| {
        (lua.load("return (function(x) return x end)(...)")).call::<Value>(arg)
    })?)?;
    let res = co.resume::<String>("abc")?;
    assert_eq!(res, "abc".to_string());
    assert_eq!(yield_count.load(Ordering::Relaxed), 3);

    //
    // Test errors in interrupts
    //
    lua.set_interrupt(|_| Err(Error::runtime("error from interrupt")));
    match f.call::<()>(()) {
        Err(Error::RuntimeError(ref msg)) => assert_eq!(msg, "error from interrupt"),
        res => panic!("expected `RuntimeError` with a specific message, got {res:?}"),
    }

    lua.remove_interrupt();

    Ok(())
}

#[test]
fn test_interrupt_callback_drop() {
    struct ReenterOnDrop(Lua);

    impl Drop for ReenterOnDrop {
        fn drop(&mut self) {
            self.0
                .load("local n = 0; for i = 1, 10 do n = n + i end")
                .exec()
                .unwrap();
            self.0.set_app_data(());
        }
    }

    for oneshot in [false, true] {
        for replacement in 0..3 {
            let lua = Lua::new();
            let guard = ReenterOnDrop(lua.clone());
            let callback = move |_: &Lua| {
                let _ = &guard;
                panic!("called a callback during drop");
            };
            let old = if oneshot {
                let handle = lua.set_interrupt_oneshot(callback);
                handle.arm();
                Some(handle)
            } else {
                lua.set_interrupt(callback);
                None
            };
            match replacement {
                0 => lua.remove_interrupt(),
                1 => lua.set_interrupt(|_| Ok(VmState::Continue)),
                _ => {
                    let _handle = lua.set_interrupt_oneshot(|_| panic!("unarmed replacement"));
                }
            }
            assert_eq!(lua.remove_app_data::<()>(), Some(()));
            if let Some(old) = old {
                assert!(!old.arm());
            }
        }
    }
}

static_assertions::assert_impl_all!(InterruptHandle: Clone, Send, Sync);

fn has_native_interrupt(lua: &Lua) -> Result<bool> {
    let mut present = false;
    unsafe {
        lua.exec_raw::<()>((), |state| {
            present = (*ffi::lua_callbacks(state)).interrupt.is_some();
        })?;
    }
    Ok(present)
}

#[test]
fn test_interrupt_oneshot() -> Result<()> {
    let lua = Lua::new();

    let f = lua.load("for i = 1, 10 do end").into_function()?;
    let calls = Arc::new(AtomicU64::new(0));
    let handle = lua.set_interrupt_oneshot({
        let calls = calls.clone();
        move |_| {
            calls.fetch_add(1, Ordering::Relaxed);
            Ok(VmState::Continue)
        }
    });
    assert!(!has_native_interrupt(&lua)?);
    f.call::<()>(())?;
    assert_eq!(calls.load(Ordering::Relaxed), 0);

    assert!(handle.clone().arm());
    handle.disarm();
    handle.disarm();
    assert!(!has_native_interrupt(&lua)?);
    f.call::<()>(())?;
    assert_eq!(calls.load(Ordering::Relaxed), 0);

    assert!(handle.arm());
    assert!(handle.clone().arm());
    // GC safepoints must not consume the pending execution interrupt.
    unsafe {
        lua.exec_raw::<()>((), |state| {
            (*ffi::lua_callbacks(state)).interrupt.unwrap()(state, 0);
        })?;
    }
    assert_eq!(calls.load(Ordering::Relaxed), 0);
    f.call::<()>(())?;
    assert_eq!(calls.load(Ordering::Relaxed), 1);
    assert!(!has_native_interrupt(&lua)?);
    f.call::<()>(())?;
    assert_eq!(calls.load(Ordering::Relaxed), 1);

    // Rearming is reusable, and dropping the handle does not cancel a pending request.
    assert!(handle.arm());
    drop(handle);
    f.call::<()>(())?;
    assert_eq!(calls.load(Ordering::Relaxed), 2);

    Ok(())
}

#[test]
fn test_interrupt_oneshot_rearm() -> Result<()> {
    use std::panic::{AssertUnwindSafe, catch_unwind};

    #[derive(Clone, Copy)]
    enum Outcome {
        Continue,
        Error,
        Panic,
    }

    // Exercise guard cleanup on normal return, error, and panic.
    for outcome in [Outcome::Continue, Outcome::Error, Outcome::Panic] {
        let lua = Lua::new();
        let f = lua.load("for i = 1, 10 do end").into_function()?;
        let calls = Arc::new(AtomicU64::new(0));
        let handle = lua.set_interrupt_oneshot({
            let calls = calls.clone();
            move |lua| {
                if calls.fetch_add(1, Ordering::Relaxed) == 0 {
                    assert!(lua.app_data_ref::<InterruptHandle>().unwrap().arm());
                    assert!(!has_native_interrupt(lua)?);
                    lua.load("for i = 1, 10 do end").exec()?;
                    assert_eq!(calls.load(Ordering::Relaxed), 1); // No recursive delivery.
                    match outcome {
                        Outcome::Continue => {}
                        Outcome::Error => return Err(Error::runtime("interrupt error")),
                        Outcome::Panic => panic!("interrupt panic"),
                    }
                }
                Ok(VmState::Continue)
            }
        });
        lua.set_app_data(handle.clone());
        handle.arm();
        let result = catch_unwind(AssertUnwindSafe(|| f.call::<()>(())));
        match outcome {
            Outcome::Continue => result.unwrap()?,
            Outcome::Error => {
                assert!(matches!(result.unwrap(), Err(Error::RuntimeError(msg)) if msg == "interrupt error"))
            }
            Outcome::Panic => assert!(result.is_err()),
        }
        f.call::<()>(())?;
        assert_eq!(calls.load(Ordering::Relaxed), 2);
        assert!(!has_native_interrupt(&lua)?);
    }

    Ok(())
}

#[test]
fn test_interrupt_oneshot_replace_during_callback() -> Result<()> {
    for persistent in [false, true] {
        let lua = Lua::new();
        let handle = lua.set_interrupt_oneshot(move |lua| {
            assert!(lua.app_data_ref::<InterruptHandle>().unwrap().arm());
            if persistent {
                lua.set_interrupt(|_| Ok(VmState::Continue));
            } else {
                let _handle = lua.set_interrupt_oneshot(|_| panic!("unarmed replacement"));
            }
            Ok(VmState::Continue)
        });
        lua.set_app_data(handle.clone());
        handle.arm();
        lua.load("for i = 1, 10 do end").exec()?;
        assert!(!handle.arm());
        // Neither finishing nor disarming the old callback may change the replacement's slot.
        handle.disarm();
        assert_eq!(has_native_interrupt(&lua)?, persistent);
    }
    Ok(())
}

#[test]
fn test_interrupt_oneshot_yield() -> Result<()> {
    let lua = Lua::new();

    let co = lua.create_thread(lua.load("for i = 1, 10 do end; return 42").into_function()?)?;
    let calls = Arc::new(AtomicU64::new(0));
    let handle = lua.set_interrupt_oneshot({
        let calls = calls.clone();
        move |_| {
            calls.fetch_add(1, Ordering::Relaxed);
            Ok(VmState::Yield)
        }
    });
    handle.arm();
    co.resume::<()>(())?;
    assert_eq!(calls.load(Ordering::Relaxed), 1); // Delivered before yielding.
    assert!(co.is_resumable());
    assert!(!has_native_interrupt(&lua)?);
    assert_eq!(co.resume::<usize>(())?, 42);
    assert!(co.is_finished());

    // A request is also consumed when yielding is not possible.
    let f = lua.create_function(|lua, ()| lua.load("return 42").eval::<usize>())?;
    handle.arm();
    assert_eq!(f.call::<usize>(())?, 42);
    assert_eq!(calls.load(Ordering::Relaxed), 2); // The handle survived the yield.
    assert!(!has_native_interrupt(&lua)?);

    Ok(())
}

#[test]
fn test_interrupt_oneshot_disarm_during_callback() -> Result<()> {
    let lua = Lua::new();

    let f = lua.load("for i = 1, 10 do end").into_function()?;
    let calls = Arc::new(AtomicU64::new(0));
    let handle = lua.set_interrupt_oneshot({
        let calls = calls.clone();
        move |lua| {
            if calls.fetch_add(1, Ordering::Relaxed) == 0 {
                let handle = lua.app_data_ref::<InterruptHandle>().unwrap();
                assert!(handle.arm());
                handle.disarm();
            }
            Ok(VmState::Continue)
        }
    });
    lua.set_app_data(handle.clone());
    handle.arm();
    f.call::<()>(())?;
    // The re-arm made during the callback must not be re-installed when the guard exits.
    assert!(!has_native_interrupt(&lua)?);
    f.call::<()>(())?;
    assert_eq!(calls.load(Ordering::Relaxed), 1);

    Ok(())
}

#[cfg(not(target_family = "wasm"))]
#[test]
fn test_interrupt_oneshot_from_another_thread() -> Result<()> {
    use std::sync::mpsc;
    use std::time::Duration;

    let lua = Lua::new();

    let (started_tx, started_rx) = mpsc::channel();
    let (armed_tx, armed_rx) = mpsc::channel::<bool>();
    lua.globals().set(
        "started",
        lua.create_function(move |_, ()| {
            started_tx.send(()).unwrap();
            assert!(armed_rx.recv_timeout(Duration::from_secs(10)).unwrap());
            Ok(())
        })?,
    )?;
    let handle = lua.set_interrupt_oneshot(|_| Err(Error::runtime("interrupted")));
    let worker = std::thread::spawn(move || {
        started_rx.recv_timeout(Duration::from_secs(10)).unwrap();
        assert!(handle.arm());
        handle.disarm();
        armed_tx.send(handle.arm()).unwrap();
    });
    let result = lua.load("started(); for i = 1, 10 do end").exec();
    worker.join().unwrap();
    assert!(matches!(result, Err(Error::RuntimeError(msg)) if msg == "interrupted"));

    Ok(())
}

#[cfg(not(target_family = "wasm"))]
#[test]
fn test_interrupt_oneshot_teardown_race() {
    use std::sync::mpsc;
    use std::time::{Duration, Instant};

    for remove in [false, true] {
        for _ in 0..64 {
            let lua = Lua::new();
            let handle = lua.set_interrupt_oneshot(|_| Ok(VmState::Continue));
            let (started_tx, started_rx) = mpsc::channel();
            let worker = std::thread::spawn(move || {
                assert!(handle.arm());
                started_tx.send(()).unwrap();
                // Alternate arm/disarm until teardown invalidates the handle.
                let deadline = Instant::now() + Duration::from_secs(10);
                while handle.arm() {
                    assert!(Instant::now() < deadline, "timed out waiting for teardown");
                    handle.disarm();
                    std::thread::yield_now();
                }
                handle.disarm();
            });
            started_rx.recv_timeout(Duration::from_secs(10)).unwrap();
            if remove {
                lua.remove_interrupt();
            } else {
                drop(lua);
            }
            worker.join().unwrap();
        }
    }
}

#[cfg(not(feature = "send"))]
#[test]
fn test_interrupt_oneshot_non_send_callback() {
    use std::rc::Rc;

    let lua = Lua::new();
    let captured = Rc::new(());
    let weak = Rc::downgrade(&captured);
    let handle = lua.set_interrupt_oneshot(move |_| {
        let _ = &captured;
        Ok(VmState::Continue)
    });
    drop(lua);
    assert!(weak.upgrade().is_none()); // Handles must not retain the callback or VM.
    assert!(!handle.arm());
}

#[test]
fn test_fflags() {
    // We cannot really on any particular feature flag to be present
    assert!(Lua::set_fflag("UnknownFlag", true).is_err());
}

#[cfg(feature = "luau-jit")]
#[test]
fn test_jit_inliner() -> Result<()> {
    let compiler = Compiler::new();
    let bytecode = compiler.compile("return 42")?;

    let lua = Lua::new();
    lua.enable_jit(false);
    lua.sandbox(true)?;
    lua.set_jit_options(mlua::state::JitOptions::new().inliner(true));

    // Enabling the inliner must not change global compiler flags.
    assert_eq!(compiler.compile("return 42")?, bytecode);

    // An inlinable helper called in a hot loop.
    let sum = lua
        .load(
            r#"
            local function add(a, b)
                return a + b + 0.5
            end
            local function caller(a, b)
                local sum = add(a, b)
                return sum - 0.5
            end
            local sum = 0
            for i = 1, 1000 do
                sum = caller(sum, i)
            end
            return sum
        "#,
        )
        .eval::<i64>()?;
    assert_eq!(sum, 500500);

    Ok(())
}

#[test]
fn test_loadstring() -> Result<()> {
    let lua = Lua::new();

    let f = lua.load(r#"loadstring("return 123")"#).eval::<Function>()?;
    assert_eq!(f.call::<i32>(())?, 123);

    let err = lua
        .load(r#"loadstring("retur 123", "chunk")"#) // typos:ignore
        .exec()
        .err()
        .unwrap();
    assert!(err.to_string().contains(
        r#"syntax error: [string "chunk"]:1: Incomplete statement: expected assignment or a function call"#
    ));

    Ok(())
}

#[test]
fn test_typeof_error() -> Result<()> {
    let lua = Lua::new();

    let err = Error::runtime("just a test error");
    let res = lua.load("return typeof(...)").call::<String>(err)?;
    assert_eq!(res, "error");

    Ok(())
}

#[test]
fn test_memory_category() -> Result<()> {
    let lua = Lua::new();

    lua.set_memory_category("main").unwrap();

    // Invalid category names should be rejected
    let err = lua.set_memory_category("invalid$");
    assert!(err.is_err());

    for i in 0..254 {
        let name = format!("category_{}", i);
        lua.set_memory_category(&name).unwrap();
    }
    // 255th category should fail
    let err = lua.set_memory_category("category_254");
    assert!(err.is_err());

    Ok(())
}

#[test]
#[cfg(not(any(all(target_arch = "wasm32", target_os = "unknown"), target_os = "wasi")))]
fn test_heap_dump() -> Result<()> {
    let lua = Lua::new();

    // Assign a new memory category and create few objects
    lua.set_memory_category("test_category")?;
    let _t = lua.create_table()?;
    let _ud = lua.create_any_userdata("hello, world")?;

    let dump = lua.heap_dump()?;

    assert!(dump.size() > 0);
    let size_by_category = dump.size_by_category();
    assert_eq!(size_by_category.len(), 2);
    assert!(size_by_category.contains_key("test_category"));
    assert!(size_by_category["main"] < dump.size());

    // Check size by type within the category
    let size_by_type = dump.size_by_type(Some("test_category"));
    assert!(!size_by_type.is_empty());
    assert!(size_by_type.contains_key("table"));
    assert!(size_by_type.contains_key("userdata"));
    // Try non-existent category
    let size_by_type2 = dump.size_by_type(Some("non_existent_category"));
    assert!(size_by_type2.is_empty());
    // Remove category filter
    let size_by_type_all = dump.size_by_type(None);
    assert!(size_by_type.len() < size_by_type_all.len());

    // Check size by userdata type within the category
    let size_by_udtype = dump.size_by_userdata(Some("test_category"));
    assert_eq!(size_by_udtype.len(), 1);
    assert!(size_by_udtype.contains_key("&str"));
    assert_eq!(size_by_udtype["&str"].0, 1);
    // Try non-existent category
    let size_by_udtype2 = dump.size_by_userdata(Some("non_existent_category"));
    assert!(size_by_udtype2.is_empty());
    // Remove category filter
    let size_by_udtype_all = dump.size_by_userdata(None);
    assert!(size_by_udtype.len() < size_by_udtype_all.len());

    Ok(())
}

#[path = "luau/require.rs"]
mod require;