mlua 0.12.2

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
#![cfg(not(feature = "luau"))]

use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Arc, Mutex};

use mlua::debug::DebugEvent;
use mlua::{Error, HookTriggers, Lua, Result, Value, VmState};

#[test]
fn test_hook_triggers() {
    let trigger = HookTriggers::new().on_calls().on_returns()
        | HookTriggers::new().every_line().every_nth_instruction(5);

    assert!(trigger.on_calls);
    assert!(trigger.on_returns);
    assert!(trigger.every_line);
    assert_eq!(trigger.every_nth_instruction, Some(5));
}

#[test]
fn test_line_counts() -> Result<()> {
    let output = Arc::new(Mutex::new(Vec::new()));
    let hook_output = output.clone();

    let lua = Lua::new();
    lua.set_hook(HookTriggers::EVERY_LINE, move |_lua, debug| {
        assert_eq!(debug.event(), DebugEvent::Line);
        hook_output.lock().unwrap().push(debug.current_line().unwrap());
        Ok(VmState::Continue)
    })?;
    lua.load(
        r#"
            local x = 2 + 3
            local y = x * 63
            local z = string.len(x..", "..y)
        "#,
    )
    .exec()?;

    lua.remove_hook();

    let output = output.lock().unwrap();
    if cfg!(feature = "luajit") && lua.load("jit.version_num").eval::<i64>()? >= 20100 {
        assert_eq!(*output, vec![2, 3, 4, 0, 4]);
    } else {
        assert_eq!(*output, vec![2, 3, 4]);
    }

    Ok(())
}

#[test]
fn test_function_calls() -> Result<()> {
    let output = Arc::new(Mutex::new(Vec::new()));
    let hook_output = output.clone();

    let lua = Lua::new();
    lua.set_hook(HookTriggers::ON_CALLS, move |_lua, debug| {
        assert_eq!(debug.event(), DebugEvent::Call);
        let names = debug.names();
        let source = debug.source();
        let name = names.name.map(|s| s.into_owned());
        hook_output.lock().unwrap().push((name, source.what));
        Ok(VmState::Continue)
    })?;

    lua.load(
        r#"
            local v = string.len("Hello World")
        "#,
    )
    .exec()?;

    lua.remove_hook();

    let output = output.lock().unwrap();
    if cfg!(feature = "luajit") && lua.load("jit.version_num").eval::<i64>()? >= 20100 {
        #[cfg(not(force_memory_limit))]
        assert_eq!(*output, vec![(None, "main"), (Some("len".to_string()), "Lua")]);
        #[cfg(force_memory_limit)]
        assert_eq!(
            *output,
            vec![(None, "C"), (None, "main"), (Some("len".to_string()), "Lua")]
        );
    } else {
        #[cfg(not(force_memory_limit))]
        assert_eq!(*output, vec![(None, "main"), (Some("len".to_string()), "C")]);
        #[cfg(force_memory_limit)]
        assert_eq!(
            *output,
            vec![(None, "C"), (None, "main"), (Some("len".to_string()), "C")]
        );
    }

    Ok(())
}

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

    lua.set_hook(HookTriggers::EVERY_LINE, |_lua, _debug| {
        Err(Error::runtime("Something happened in there!"))
    })?;

    let err = lua.load("x = 1").exec().expect_err("panic didn't propagate");
    match err {
        Error::RuntimeError(msg) => assert_eq!(msg, "Something happened in there!"),
        err => panic!("expected `RuntimeError` with a specific message, got {err:?}"),
    }

    Ok(())
}

#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_panic_during_callback_traceback() -> Result<()> {
    use std::panic::{AssertUnwindSafe, catch_unwind};

    let lua = Lua::new();
    if cfg!(feature = "luajit") && lua.set_memory_limit(0).is_err() {
        return Ok(());
    }
    let callback = lua.create_function(|lua, ()| -> Result<()> {
        lua.set_hook(HookTriggers::ON_CALLS, |lua, _| {
            lua.remove_hook();
            panic!("traceback hook panic");
        })?;
        // use protected traceback generation
        lua.set_memory_limit(usize::MAX)?;
        Err(Error::runtime("callback error"))
    })?;
    lua.globals().set("callback", callback)?;

    let panic = catch_unwind(AssertUnwindSafe(|| lua.load("callback()").exec()))
        .expect_err("hook panic did not propagate");
    assert_eq!(panic.downcast_ref::<&str>(), Some(&"traceback hook panic"));
    assert!(
        lua.inspect_stack(0, |_| ()).is_none(),
        "Lua frames were not restored"
    );
    Ok(())
}

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

    // For LuaJIT disable JIT, as compiled code does not trigger hooks
    #[cfg(feature = "luajit")]
    lua.load("jit.off()").exec()?;

    let max_instructions = AtomicI64::new(10000);
    lua.set_hook(
        HookTriggers::new().every_nth_instruction(30),
        move |_lua, debug| {
            assert_eq!(debug.event(), DebugEvent::Count);
            if max_instructions.fetch_sub(30, Ordering::Relaxed) <= 30 {
                Err(Error::runtime("time's up"))
            } else {
                Ok(VmState::Continue)
            }
        },
    )?;

    lua.globals().set("x", Value::Integer(0))?;
    let _ = lua
        .load(
            r#"
                for i = 1, 10000 do
                    x = x + 1
                end
            "#,
        )
        .exec()
        .expect_err("instruction limit didn't occur");

    Ok(())
}

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

    lua.set_hook(HookTriggers::new().every_nth_instruction(1), |_lua, _debug| {
        Err(Error::runtime("this hook should've been removed by this time"))
    })?;

    assert!(lua.load("local x = 1").exec().is_err());
    lua.remove_hook();
    assert!(lua.load("local x = 1").exec().is_ok());

    Ok(())
}

// Having the code compiled (even not run) on macos and luajit causes a memory reference issue
// See https://github.com/LuaJIT/LuaJIT/issues/1099
#[cfg(not(all(feature = "luajit", target_os = "macos")))]
#[test]
fn test_hook_swap_within_hook() -> Result<()> {
    thread_local! {
        static TL_LUA: std::cell::RefCell<Option<Lua>> = Default::default();
    }

    TL_LUA.with(|tl| {
        *tl.borrow_mut() = Some(Lua::new());
    });

    TL_LUA.with(|tl| {
        tl.borrow()
            .as_ref()
            .unwrap()
            .set_hook(HookTriggers::EVERY_LINE, move |lua, _debug| {
                lua.globals().set("ok", 1i64)?;
                TL_LUA.with(|tl| {
                    tl.borrow()
                        .as_ref()
                        .unwrap()
                        .set_hook(HookTriggers::EVERY_LINE, move |lua, _debug| {
                            lua.load(
                                r#"
                                    if ok ~= nil then
                                        ok = ok + 1
                                    end
                                "#,
                            )
                            .exec()
                            .expect("exec failure within hook");
                            TL_LUA.with(|tl| {
                                tl.borrow().as_ref().unwrap().remove_hook();
                            });
                            Ok(VmState::Continue)
                        })
                })?;
                Ok(VmState::Continue)
            })
    })?;

    TL_LUA.with(|tl| {
        let tl = tl.borrow();
        let lua = tl.as_ref().unwrap();
        lua.load(
            r#"
                local x = 1
                x = 2
                local y = 3
            "#,
        )
        .exec()?;
        assert_eq!(lua.globals().get::<i64>("ok")?, 2);
        Ok(())
    })
}

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

    let func = lua
        .load(
            r#"
            local x = 2 + 3
            local y = x * 63
            local z = string.len(x..", "..y)
        "#,
        )
        .into_function()?;
    let co = lua.create_thread(func)?;

    let output = Arc::new(Mutex::new(Vec::new()));
    let hook_output = output.clone();
    co.set_hook(HookTriggers::EVERY_LINE, move |_lua, debug| {
        assert_eq!(debug.event(), DebugEvent::Line);
        hook_output.lock().unwrap().push(debug.current_line().unwrap());
        Ok(VmState::Continue)
    })?;

    co.resume::<()>(())?;
    lua.remove_hook();

    let output = output.lock().unwrap();
    if cfg!(feature = "luajit") && lua.load("jit.version_num").eval::<i64>()? >= 20100 {
        assert_eq!(*output, vec![2, 3, 4, 0, 4]);
    } else {
        assert_eq!(*output, vec![2, 3, 4]);
    }

    Ok(())
}

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

    let func = lua
        .load(
            r#"
            local x = 2 + 3
            local y = x * 63
            local z = string.len(x..", "..y)
        "#,
        )
        .into_function()?;
    let co = lua.create_thread(func)?;

    co.set_hook(HookTriggers::EVERY_LINE, move |_lua, _debug| Ok(VmState::Yield))?;

    #[cfg(any(feature = "lua55", feature = "lua54", feature = "lua53"))]
    {
        assert!(co.resume::<()>(()).is_ok());
        assert!(co.resume::<()>(()).is_ok());
        assert!(co.resume::<()>(()).is_ok());
        assert!(co.resume::<()>(()).is_ok());
        assert!(co.is_finished());
    }
    #[cfg(any(feature = "lua51", feature = "lua52", feature = "luajit"))]
    {
        assert!(
            matches!(co.resume::<()>(()), Err(Error::RuntimeError(err)) if err.contains("attempt to yield from a hook"))
        );
        assert!(co.is_error());
    }

    Ok(())
}

#[test]
#[cfg(any(feature = "lua55", feature = "lua54", feature = "lua53"))]
fn test_hook_yield_preserves_stack() -> Result<()> {
    let lua = Lua::new();

    let func = lua
        .load(
            r#"
            local x = { value = 40 }
            local y = 2
            return x.value + y
        "#,
        )
        .into_function()?;
    let co = lua.create_thread(func)?;

    let yielded = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let yielded2 = yielded.clone();
    co.set_hook(HookTriggers::EVERY_LINE, move |_lua, debug| {
        if debug.current_line() == Some(4) && !yielded2.swap(true, Ordering::Relaxed) {
            return Ok(VmState::Yield);
        }
        Ok(VmState::Continue)
    })?;

    co.resume::<()>(())?;
    assert!(yielded.load(Ordering::Relaxed));
    co.remove_hook();
    lua.gc_collect()?;
    assert_eq!(co.resume::<i32>(())?, 42);

    Ok(())
}

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

    let counter = Arc::new(AtomicI64::new(0));
    let hook_counter = counter.clone();
    lua.set_global_hook(HookTriggers::EVERY_LINE, move |_lua, debug| {
        assert_eq!(debug.event(), DebugEvent::Line);
        hook_counter.fetch_add(1, Ordering::Relaxed);
        Ok(VmState::Continue)
    })?;

    let thread = lua.create_thread(
        lua.load(
            r#"
            local x = 2 + 3
            local y = x * 63
            coroutine.yield()
            local z = string.len(x..", "..y)
        "#,
        )
        .into_function()?,
    )?;

    thread.resume::<()>(()).unwrap();
    lua.remove_global_hook();
    thread.resume::<()>(()).unwrap();
    assert!(thread.is_finished());
    assert_eq!(counter.load(Ordering::Relaxed), 3);

    Ok(())
}

#[test]
fn test_global_hook_callback_drop() -> Result<()> {
    struct ReenterOnDrop(Lua);

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

    for replace in [false, true] {
        let lua = Lua::new();
        let guard = ReenterOnDrop(lua.clone());
        lua.set_global_hook(HookTriggers::EVERY_LINE, move |_, _| {
            let _ = &guard;
            panic!("called a callback during drop");
        })?;
        if replace {
            lua.set_global_hook(HookTriggers::EVERY_LINE, |_, _| Ok(VmState::Continue))?;
        } else {
            lua.remove_global_hook();
        }
        assert_eq!(lua.remove_app_data::<()>(), Some(()));
    }
    Ok(())
}

#[test]
fn test_hook_memory_error() -> Result<()> {
    let lua = Lua::new();
    if cfg!(feature = "luajit") && lua.set_memory_limit(0).is_err() {
        return Ok(());
    }

    let arc = Arc::new(());
    let captured = arc.clone();
    lua.set_memory_limit(1)?;
    assert!(matches!(
        lua.set_hook(HookTriggers::EVERY_LINE, move |_, _| {
            let _ = &captured;
            Ok(VmState::Continue)
        }),
        Err(Error::MemoryError(_))
    ));
    drop(lua);
    assert_eq!(Arc::strong_count(&arc), 1);

    Ok(())
}