luars 0.20.0

A library for lua 5.5 runtime implementation 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
#[cfg(test)]
mod tests {
    use std::cell::Cell;

    #[cfg(feature = "sandbox")]
    use crate::SandboxConfig;
    #[cfg(feature = "serde")]
    use crate::lua_api::Value;
    use crate::{
        LuaUserData, SafeOption, Stdlib,
        lua_api::{Function, Lua, Table},
        lua_methods,
    };
    #[cfg(feature = "serde")]
    use serde::{Deserialize, Serialize};

    #[cfg(feature = "serde")]
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct ApiConfig {
        host: String,
        port: u16,
        tags: Vec<String>,
    }

    #[derive(LuaUserData)]
    struct ApiCounter {
        pub count: i64,
    }

    #[lua_methods]
    impl ApiCounter {
        pub fn inc(&mut self, delta: i64) {
            self.count += delta;
        }

        pub fn get(&self) -> i64 {
            self.count
        }
    }

    #[test]
    fn eval_and_typed_globals_work() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        lua.set_global("name", "Lua").unwrap();

        let result: String = lua.eval("return 'hello ' .. name").unwrap();
        assert_eq!(result, "hello Lua");
    }

    #[test]
    fn register_and_call_typed_function() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        lua.register_function("sum", |a: i64, b: i64| a + b)
            .unwrap();

        let result: i64 = lua.eval("return sum(20, 22)").unwrap();
        assert_eq!(result, 42);
    }

    #[test]
    fn call_global_for_lua_defined_function() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();
        lua.load("function mul(a, b) return a * b end")
            .exec()
            .unwrap();

        let result: i64 = lua.call_global1("mul", (6, 7)).unwrap();
        assert_eq!(result, 42);
    }

    #[test]
    fn high_level_collect_garbage_works() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        lua.load(
            r#"
            local t = {}
            for i = 1, 200 do
                t[i] = { index = i, payload = string.rep("x", 32) }
            end
            t = nil
            "#,
        )
        .exec()
        .unwrap();

        lua.collect_garbage().unwrap();

        let answer: i64 = lua.eval("return 40 + 2").unwrap();
        assert_eq!(answer, 42);
    }

    #[test]
    fn safe_table_round_trip() {
        let mut lua = Lua::new(SafeOption::default());
        let table = lua.create_table_with_capacity(0, 2).unwrap();

        lua.table_set(&table, "host", "localhost").unwrap();
        lua.table_set(&table, "port", 8080_i64).unwrap();
        lua.set_global_table("config", &table).unwrap();

        let config = lua.get_table("config").unwrap().unwrap();
        let host: String = config.get("host").unwrap();
        let port: i64 = config.get("port").unwrap();

        assert_eq!(host, "localhost");
        assert_eq!(port, 8080);
    }

    #[test]
    fn globals_and_generic_table_api_feel_like_mlua() {
        let mut lua = Lua::new(SafeOption::default());
        let globals = lua.globals();

        globals.set("host", "localhost").unwrap();
        globals.set("port", 8080_i64).unwrap();

        assert!(globals.contains_key("host").unwrap());
        assert_eq!(globals.get::<String>("host").unwrap(), "localhost");
        assert_eq!(globals.raw_get::<i64>("port").unwrap(), 8080);
    }

    #[test]
    fn create_table_from_and_sequence_from_work() {
        let mut lua = Lua::new(SafeOption::default());

        let config = lua
            .create_table_from([("host", "localhost"), ("mode", "dev")])
            .unwrap();
        let seq = lua.create_sequence_from([10_i64, 20_i64, 30_i64]).unwrap();

        assert_eq!(config.get::<String>("host").unwrap(), "localhost");
        assert_eq!(config.pairs::<String, String>().unwrap().len(), 2);
        assert_eq!(seq.sequence_values::<i64>().unwrap(), vec![10, 20, 30]);
    }

    #[test]
    fn create_function_and_convert_helpers_work() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let double = lua.create_function(|x: i64| x * 2).unwrap();
        lua.globals().set("double", double.clone()).unwrap();

        let packed = lua.pack("42").unwrap();
        let unpacked: String = lua.unpack(packed).unwrap();
        let converted: i64 = lua.convert(123_i64).unwrap();
        let result: i64 = lua.eval("return double(21)").unwrap();

        assert_eq!(unpacked, "42");
        assert_eq!(converted, 123);
        assert_eq!(result, 42);
    }

    #[test]
    fn table_objectlike_helpers_work() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let obj: Table = lua
            .load(
                r#"
                return {
                    nested = { answer = 42 },
                    add = function(a, b) return a + b end,
                    scale = function(self, x) return self.factor * x end,
                    factor = 3,
                }
                "#,
            )
            .eval()
            .unwrap();

        assert_eq!(obj.get_path::<i64>(&["nested", "answer"]).unwrap(), 42);
        assert_eq!(obj.call_function::<_, i64>("add", (20, 22)).unwrap(), 42);
        assert_eq!(obj.call_method1::<_, i64>("scale", 14_i64).unwrap(), 42);
    }

    #[test]
    fn safe_value_handle_supports_string_and_downcasts() {
        let mut lua = Lua::new(SafeOption::default());

        let string_value = lua.pack("hello").unwrap();
        let table = lua.create_table_from([("answer", 42_i64)]).unwrap();
        let table_value = lua.pack(table).unwrap();
        let userdata = lua.create_userdata(ApiCounter { count: 1 }).unwrap();
        let userdata_value = lua.pack(userdata.clone()).unwrap();

        assert_eq!(string_value.type_name(), "string");
        assert_eq!(string_value.as_string().unwrap(), "hello");
        assert_eq!(string_value.to_string_lossy(), "hello");
        assert_eq!(
            string_value.as_string_handle().unwrap().as_str(),
            Some("hello")
        );

        let table = table_value.as_table().unwrap();
        assert_eq!(table.get::<i64>("answer").unwrap(), 42);

        let counter = userdata_value.as_userdata::<ApiCounter>().unwrap();
        assert_eq!(counter.get().unwrap().count, 1);

        let converted: String = string_value.get().unwrap();
        assert_eq!(converted, "hello");
    }

    #[test]
    fn high_level_userdata_api_works() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let type_table = lua.register_type::<ApiCounter>("Counter").unwrap();
        assert!(type_table.raw_len().is_ok());

        let counter = lua.create_userdata(ApiCounter { count: 1 }).unwrap();
        lua.globals().set("counter", counter.clone()).unwrap();
        lua.load("counter:inc(41)").exec().unwrap();

        assert_eq!(counter.get().unwrap().count, 42);
        assert_eq!(lua.load("return counter:get()").eval::<i64>().unwrap(), 42);
    }

    #[test]
    fn borrowed_userdata_api_works() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let mut counter = ApiCounter { count: 2 };
        let borrowed = unsafe { lua.create_userdata_ref(&mut counter).unwrap() };
        lua.globals().set("borrowed", borrowed.clone()).unwrap();
        lua.load("borrowed:inc(40)").exec().unwrap();

        assert_eq!(counter.count, 42);
        assert_eq!(borrowed.get().unwrap().count, 42);
    }

    #[test]
    fn scope_supports_non_static_functions() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let base = 40_i64;
        lua.scope(|scope| {
            let add_base = scope.create_function_with(&base, |base: &i64, x: i64| x + *base)?;
            scope.globals().set("add_base", &add_base)?;

            let result: i64 = scope.load("return add_base(2)").eval()?;
            assert_eq!(result, 42);
            Ok(())
        })
        .unwrap();

        assert!(lua.load("return add_base(1)").eval::<i64>().is_err());
    }

    #[test]
    fn scope_supports_borrowed_userdata() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let mut counter = ApiCounter { count: 1 };
        lua.scope(|scope| {
            let mut borrowed = scope.create_userdata_ref(&mut counter)?;
            scope.globals().set("borrowed", &borrowed)?;

            let count: i64 = scope.load("return borrowed.count").eval()?;
            assert_eq!(count, 1);
            let called: i64 = scope
                .load("borrowed:inc(41); return borrowed:get()")
                .eval()?;
            assert_eq!(called, 42);
            let reassigned: i64 = scope
                .load("borrowed.count = borrowed.count + 1; return borrowed.count")
                .eval()?;
            assert_eq!(reassigned, 43);

            borrowed.get_mut()?.inc(41);
            assert_eq!(borrowed.get()?.count, 84);
            Ok(())
        })
        .unwrap();

        assert_eq!(counter.count, 84);

        assert!(lua.load("return borrowed:get()").eval::<i64>().is_err());
        assert!(lua.load("borrowed.count = 1").exec().is_err());
    }

    #[test]
    fn scope_function_with_borrowed_state_works() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let total = Cell::new(0_i64);
        lua.scope(|scope| {
            let push = scope.create_function_with(&total, |total: &Cell<i64>, delta: i64| {
                total.set(total.get() + delta);
                total.get()
            })?;
            scope.globals().set("push_total", &push)?;

            let value: i64 = scope
                .load("return push_total(19) + push_total(23)")
                .eval()?;
            assert_eq!(value, 61);
            Ok(())
        })
        .unwrap();

        assert_eq!(total.get(), 42);
    }

    #[test]
    fn scope_function_mut_with_borrowed_state_works() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let mut total = 0_i64;
        lua.scope(|scope| {
            let push =
                scope.create_function_mut_with(&mut total, |total: &mut i64, delta: i64| {
                    *total += delta;
                    *total
                })?;
            scope.globals().set("push_total_mut", &push)?;

            let value: i64 = scope
                .load("return push_total_mut(19) + push_total_mut(23)")
                .eval()?;
            assert_eq!(value, 61);
            Ok(())
        })
        .unwrap();

        assert_eq!(total, 42);
    }

    #[test]
    fn scope_function_with_borrowed_reference_works() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let base = 40_i64;
        lua.scope(|scope| {
            let add_base = scope.create_function_with(&base, |base: &i64, x: i64| x + *base)?;
            scope.globals().set("add_base", &add_base)?;

            let result: i64 = scope.load("return add_base(2)").eval()?;
            assert_eq!(result, 42);
            Ok(())
        })
        .unwrap();
    }

    #[test]
    fn chunk_builder_exec_eval_and_into_function_work() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        lua.load("answer = 41").set_name("init.lua").exec().unwrap();
        let answer: i64 = lua.load("return answer + 1").eval().unwrap();
        let add = lua
            .load("local a, b = ...; return a + b")
            .set_name("adder.lua")
            .into_function()
            .unwrap();

        assert_eq!(answer, 42);
        assert_eq!(add.call1::<_, i64>((20, 22)).unwrap(), 42);
    }

    #[tokio::test]
    async fn high_level_async_api_exec_and_call_work() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        lua.register_async_function("double_async", |x: i64| async move { Ok(x * 2) })
            .unwrap();
        lua.load(
            r#"
            function add_async(a, b)
                return double_async(a + b)
            end
            "#,
        )
        .exec()
        .unwrap();

        let chunk_value: i64 = lua
            .load("return double_async(21)")
            .eval_async()
            .await
            .unwrap();
        let global_value: i64 = lua
            .call_async_global1("add_async", (20_i64, 1_i64))
            .await
            .unwrap();
        let compiled: Function = lua
            .load("return function(x) return double_async(x) end")
            .eval()
            .unwrap();
        let function_value: i64 = lua.call_async1(&compiled, 21_i64).await.unwrap();

        assert_eq!(chunk_value, 42);
        assert_eq!(global_value, 42);
        assert_eq!(function_value, 42);
    }

    #[cfg(feature = "sandbox")]
    #[test]
    fn high_level_sandbox_api_supports_injected_globals_and_isolation() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();
        lua.register_function("greet", |name: String| format!("hello, {name}"))
            .unwrap();

        let mut config = SandboxConfig::default();
        lua.sandbox_capture_global(&mut config, "greet").unwrap();
        let value: String = lua
            .load_sandboxed(
                r#"
                sandbox_value = 41
                return greet("sandbox")
                "#,
                &config,
            )
            .eval()
            .unwrap();

        assert_eq!(value, "hello, sandbox");
        assert!(lua.get_global::<i64>("sandbox_value").unwrap().is_none());
    }

    #[test]
    fn table_and_function_convert_from_lua() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let table: Table = lua
            .load("return { host = 'localhost', port = 8080 }")
            .eval()
            .unwrap();
        let function: Function = lua
            .load("return function(x) return x * 2 end")
            .eval()
            .unwrap();

        assert_eq!(table.get::<String>("host").unwrap(), "localhost");
        assert_eq!(table.get::<i64>("port").unwrap(), 8080);
        assert_eq!(function.call1::<_, i64>(21).unwrap(), 42);
    }

    #[test]
    fn high_level_lua_install_library_works() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        let module = crate::lua_module!("hostlib", {
            "answer" => |l| {
                l.push_value(crate::LuaValue::integer(42))?;
                Ok(1)
            },
            value "name" => |vm| vm.create_string("hostlib"),
        });

        lua.install_library(module).unwrap();

        let answer: i64 = lua.load("return hostlib.answer()").eval().unwrap();
        let name: String = lua.load("return hostlib.name").eval().unwrap();
        assert_eq!(answer, 42);
        assert_eq!(name, "hostlib");
    }

    #[test]
    fn high_level_lua_install_preload_library_works() {
        let mut lua = Lua::new(SafeOption::default());
        lua.open_stdlib(Stdlib::All).unwrap();

        lua.install_library(crate::lua_preload_module!("test_install_module" => |l| {
            let table = l.create_table(0, 1)?;
            let key = l.create_string("value")?;
            l.vm_mut().raw_set(&table, key, crate::LuaValue::integer(42));
            l.push_value(table)?;
            Ok(1)
        }))
        .unwrap();

        let value: i64 = lua
            .load("local mod = require('test_install_module'); return mod.value")
            .eval()
            .unwrap();

        assert_eq!(value, 42);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn table_serde_json_round_trip_works() {
        let mut lua = Lua::new(SafeOption::default());
        let table = lua
            .create_table_from([("host", "localhost"), ("port", "8080")])
            .unwrap();
        table
            .set(
                "nested",
                lua.create_sequence_from([1_i64, 2_i64, 3_i64]).unwrap(),
            )
            .unwrap();

        let json = table.to_json_value().unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "host": "localhost",
                "port": "8080",
                "nested": [1, 2, 3]
            })
        );

        let encoded = serde_json::to_value(&table).unwrap();
        assert_eq!(encoded, json);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn table_from_json_and_to_serde_work() {
        let mut lua = Lua::new(SafeOption::default());
        let table = Table::from_json_value(
            &mut lua,
            &serde_json::json!({
                "host": "127.0.0.1",
                "port": 8080,
                "tags": ["dev", "edge"]
            }),
        )
        .unwrap();

        let config: ApiConfig = table.to_serde().unwrap();
        assert_eq!(
            config,
            ApiConfig {
                host: "127.0.0.1".to_string(),
                port: 8080,
                tags: vec!["dev".to_string(), "edge".to_string()],
            }
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn table_from_serde_works() {
        let mut lua = Lua::new(SafeOption::default());
        let input = ApiConfig {
            host: "localhost".to_string(),
            port: 3000,
            tags: vec!["api".to_string(), "beta".to_string()],
        };

        let table = Table::from_serde(&mut lua, &input).unwrap();
        assert_eq!(table.get::<String>("host").unwrap(), "localhost");
        assert_eq!(table.get::<i64>("port").unwrap(), 3000);
        assert_eq!(
            table
                .get::<Table>("tags")
                .unwrap()
                .sequence_values::<String>()
                .unwrap(),
            vec!["api".to_string(), "beta".to_string()]
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn value_serde_scalar_round_trip_works() {
        let mut lua = Lua::new(SafeOption::default());
        let value = lua.pack(42_i64).unwrap();

        assert_eq!(value.to_json_value().unwrap(), serde_json::json!(42));
        assert_eq!(serde_json::to_value(&value).unwrap(), serde_json::json!(42));

        let decoded: i64 = value.to_serde().unwrap();
        assert_eq!(decoded, 42);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn value_from_json_and_from_serde_work() {
        let mut lua = Lua::new(SafeOption::default());

        let from_json = Value::from_json_value(
            &mut lua,
            &serde_json::json!({
                "host": "127.0.0.1",
                "port": 8081,
                "tags": ["prod", "edge"]
            }),
        )
        .unwrap();
        let config: ApiConfig = from_json.to_serde().unwrap();
        assert_eq!(
            config,
            ApiConfig {
                host: "127.0.0.1".to_string(),
                port: 8081,
                tags: vec!["prod".to_string(), "edge".to_string()],
            }
        );

        let from_serde = Value::from_serde(
            &mut lua,
            &ApiConfig {
                host: "localhost".to_string(),
                port: 3001,
                tags: vec!["api".to_string()],
            },
        )
        .unwrap();

        let table = from_serde.as_table().unwrap();
        assert_eq!(table.get::<String>("host").unwrap(), "localhost");
        assert_eq!(table.get::<i64>("port").unwrap(), 3001);
        assert_eq!(
            table
                .get::<Table>("tags")
                .unwrap()
                .sequence_values::<String>()
                .unwrap(),
            vec!["api".to_string()]
        );
    }

    #[test]
    fn test_userdata() {
        #[derive(Clone, Debug, LuaUserData)]
        struct RustStruct {
            a: i32,
            b: i32,
        }

        #[lua_methods]
        impl RustStruct {}

        let mut l = Lua::new(SafeOption::default());
        let t = l.create_table().unwrap();
        t.set(1, RustStruct { a: 1, b: 2 }).unwrap();
        let seq = t.sequence_values::<RustStruct>().unwrap();
        assert_eq!(seq.len(), 1);
        assert_eq!(seq[0].a, 1);
        assert_eq!(seq[0].b, 2);
    }
}