luau 0.732.0

Safe lifetime-bound Rust embedding API for the Luau runtime
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
use luau_common::ByteSlice;
use luau_vm::VmErrorResult;
use luau_vm::internal::RawHandle;
use luau_vm::internal::api::RawStackAccess;
use luau_vm::internal::table::Table as VmTable;
use luau_vm::thread::{LUA_GLOBALS_INDEX, LUA_MULTRET, StackGuard, Thread as VmThread};

use crate::error::Error;
use crate::function::Function;
use crate::lua::{Lua, LuaRef};
use crate::object::{self, ObjectLike};
use crate::thread::Thread;
use crate::value::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, Value, ValueRef};

mod formatting;
mod iteration;
mod sequence;

pub use iteration::TablePairs;
pub use sequence::TableSequence;

/// A handle to a Luau table.
pub struct Table<'lua> {
    reference: ValueRef<'lua>,
    table: VmTable,
}

impl Lua {
    /// Returns the global environment.
    pub fn globals(&self) -> Result<Table<'_>, Error> {
        self.lua_ref().globals()
    }

    /// Creates an empty table.
    pub fn create_table(&self) -> Result<Table<'_>, Error> {
        self.lua_ref().create_table()
    }

    /// Creates an empty table with array and record capacity hints.
    pub fn create_table_with_capacity(
        &self,
        array_size: usize,
        record_size: usize,
    ) -> Result<Table<'_>, Error> {
        self.lua_ref()
            .create_table_with_capacity(array_size, record_size)
    }

    /// Creates a table from key-value pairs.
    pub fn create_table_from<'lua, K, V>(
        &'lua self,
        values: impl IntoIterator<Item = (K, V)>,
    ) -> Result<Table<'lua>, Error>
    where
        K: IntoLua<'lua>,
        V: IntoLua<'lua>,
    {
        self.lua_ref().create_table_from(values)
    }

    /// Creates a sequence table from values, using keys starting at 1.
    pub fn create_sequence_from<'lua, T>(
        &'lua self,
        values: impl IntoIterator<Item = T>,
    ) -> Result<Table<'lua>, Error>
    where
        T: IntoLua<'lua>,
    {
        self.lua_ref().create_sequence_from(values)
    }
}

impl<'lua> LuaRef<'lua> {
    /// Returns the active thread's global environment.
    pub fn globals(&self) -> Result<Table<'lua>, Error> {
        unsafe {
            let thread = self.as_vm();
            let _stack = StackGuard::new(thread);
            let safe_thread = self.current_thread();
            thread
                .push_value(LUA_GLOBALS_INDEX)
                .map_err(|exit| Error::from_thread_exit(thread, exit))?;
            Table::from_stack(&safe_thread, -1)
                .map_err(|exit| Error::from_thread_exit(thread, exit))
        }
    }

    /// Creates an empty table.
    pub fn create_table(&self) -> Result<Table<'lua>, Error> {
        self.current_thread().create_table()
    }

    /// Creates an empty table with array and record capacity hints.
    pub fn create_table_with_capacity(
        &self,
        array_size: usize,
        record_size: usize,
    ) -> Result<Table<'lua>, Error> {
        self.current_thread()
            .create_table_with_capacity(array_size, record_size)
    }

    /// Creates a table from key-value pairs.
    pub fn create_table_from<K, V>(
        &self,
        values: impl IntoIterator<Item = (K, V)>,
    ) -> Result<Table<'lua>, Error>
    where
        K: IntoLua<'lua>,
        V: IntoLua<'lua>,
    {
        let values = values.into_iter();
        let table = self.create_table_with_capacity(0, values.size_hint().0)?;
        for (key, value) in values {
            table.raw_set(key, value)?;
        }
        Ok(table)
    }

    /// Creates a sequence table from values, using keys starting at 1.
    pub fn create_sequence_from<T>(
        &self,
        values: impl IntoIterator<Item = T>,
    ) -> Result<Table<'lua>, Error>
    where
        T: IntoLua<'lua>,
    {
        let values = values.into_iter();
        let table = self.create_table_with_capacity(values.size_hint().0, 0)?;
        for (index, value) in values.enumerate() {
            table.raw_seti(
                index
                    .checked_add(1)
                    .ok_or_else(Error::index_out_of_bounds)?,
                value,
            )?;
        }
        Ok(table)
    }
}

impl<'lua> Thread<'lua> {
    pub(crate) fn create_table(&self) -> Result<Table<'lua>, Error> {
        self.create_table_with_capacity(0, 0)
    }

    pub(crate) fn create_table_with_capacity(
        &self,
        array_size: usize,
        record_size: usize,
    ) -> Result<Table<'lua>, Error> {
        unsafe {
            let thread = self.as_vm();
            let _stack = StackGuard::new(thread);
            thread
                .create_table(array_size, record_size)
                .map_err(|exit| Error::from_thread_exit(thread, exit))?;
            Table::from_stack(self, -1).map_err(|exit| Error::from_thread_exit(thread, exit))
        }
    }
}

impl<'lua> Table<'lua> {
    pub(crate) unsafe fn from_stack(thread: &Thread<'lua>, index: i32) -> VmErrorResult<Self> {
        let stack_thread = thread.as_vm();
        debug_assert_ne!(unsafe { stack_thread.is_table(index) }, 0);
        let table = unsafe {
            stack_thread
                .to_object(index)
                .expect("table stack slot should contain a table")
                .table_value()
        };
        Ok(Self {
            reference: ValueRef::from_stack(thread, index)?,
            table,
        })
    }

    /// Creates another rooted handle to this table.
    pub fn try_clone(&self) -> Result<Self, Error> {
        Ok(Self {
            reference: self.reference.try_clone()?,
            table: self.table,
        })
    }

    /// Compares two tables using Luau's equality semantics.
    ///
    /// This may invoke the `__eq` metamethod.
    pub fn equals(&self, other: &Self) -> Result<bool, Error> {
        unsafe {
            let thread = self.thread();
            let vm_thread = thread.as_vm();
            let _stack = StackGuard::new(vm_thread);

            self.push_to(&thread)?;
            other.push_to(&thread)?;
            vm_thread
                .equal(-2, -1)
                .map(|equal| equal != 0)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))
        }
    }

    /// Gets a value using Luau indexing semantics.
    ///
    /// This may invoke the `__index` metamethod. Use [`Table::raw_get`] to
    /// bypass metamethods.
    pub fn get<V>(&self, key: impl IntoLua<'lua>) -> Result<V, Error>
    where
        V: FromLua<'lua>,
    {
        unsafe {
            let thread = self.thread();
            let vm_thread = thread.as_vm();
            let _stack = StackGuard::new(vm_thread);

            self.push_to(&thread)?;
            let table_index = vm_thread.get_top();
            key.push_into_stack(&thread)?;
            vm_thread
                .get_table(table_index)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))?;
            V::from_stack(&thread, -1)
        }
    }

    /// Gets a value without invoking metamethods.
    pub fn raw_get<V>(&self, key: impl IntoLua<'lua>) -> Result<V, Error>
    where
        V: FromLua<'lua>,
    {
        unsafe {
            let thread = self.reference.thread();
            let vm_thread = thread.as_vm();
            let _stack = StackGuard::new(vm_thread);

            self.push_to(&thread)?;
            let table_index = vm_thread.get_top();
            key.push_into_stack(&thread)?;
            vm_thread.raw_get(table_index);

            V::from_stack(&thread, -1)
        }
    }

    /// Returns whether indexing this table produces a non-`nil` value.
    ///
    /// This may invoke the `__index` metamethod.
    pub fn contains_key(&self, key: impl IntoLua<'lua>) -> Result<bool, Error> {
        self.get::<Value<'lua>>(key)
            .map(|value| value != Value::Nil)
    }

    /// Sets a value using Luau assignment semantics.
    ///
    /// This may invoke the `__newindex` metamethod. Use [`Table::raw_set`] to
    /// bypass metamethods.
    pub fn set(&self, key: impl IntoLua<'lua>, value: impl IntoLua<'lua>) -> Result<(), Error> {
        self.invalidate_safe_env();
        unsafe {
            let thread = self.thread();
            let vm_thread = thread.as_vm();
            let _stack = StackGuard::new(vm_thread);

            self.push_to(&thread)?;
            let table_index = vm_thread.get_top();
            key.push_into_stack(&thread)?;
            value.push_into_stack(&thread)?;
            vm_thread
                .set_table(table_index)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))?;
        }
        Ok(())
    }

    /// Sets a key-value pair without invoking metamethods.
    pub fn raw_set(&self, key: impl IntoLua<'lua>, value: impl IntoLua<'lua>) -> Result<(), Error> {
        self.invalidate_safe_env();
        unsafe {
            let thread = self.reference.thread();
            let vm_thread = thread.as_vm();
            let _stack = StackGuard::new(vm_thread);

            self.push_to(&thread)?;
            let table_index = vm_thread.get_top();
            key.push_into_stack(&thread)?;
            value.push_into_stack(&thread)?;
            vm_thread
                .raw_set(table_index)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))?;
        }
        Ok(())
    }

    /// Removes all entries while retaining the table's allocated capacity.
    pub fn clear(&self) -> Result<(), Error> {
        self.invalidate_safe_env();
        unsafe {
            let thread = self.reference.thread();
            let vm_thread = thread.as_vm();
            let _stack = StackGuard::new(vm_thread);
            self.push_to(&thread)?;
            vm_thread
                .clear_table(-1)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))?;
        }
        Ok(())
    }

    /// Returns this table's metatable.
    pub fn metatable(&self) -> Result<Option<Self>, Error> {
        unsafe {
            let thread = self.reference.thread();
            let vm_thread = thread.as_vm();
            let _stack = StackGuard::new(vm_thread);
            let Some(metatable) = self.table.metatable() else {
                return Ok(None);
            };

            vm_thread
                .push_table(metatable)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))?;
            Table::from_stack(&thread, -1)
                .map(Some)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))
        }
    }

    /// Sets or removes this table's metatable.
    pub fn set_metatable(&self, metatable: Option<&Self>) -> Result<(), Error> {
        self.invalidate_safe_env();
        unsafe {
            let thread = self.reference.thread();
            let vm_thread = thread.as_vm();
            let _stack = StackGuard::new(vm_thread);
            self.push_to(&thread)?;
            let table_index = vm_thread.get_top();
            match metatable {
                Some(metatable) => metatable.push_to(&thread)?,
                None => vm_thread
                    .push_nil()
                    .map_err(|exit| Error::from_thread_exit(vm_thread, exit))?,
            }
            vm_thread
                .set_metatable(table_index)
                .map(drop)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))?;
        }
        Ok(())
    }

    /// Returns whether this table has a metatable.
    pub fn has_metatable(&self) -> bool {
        unsafe { self.table.metatable().is_some() }
    }

    /// Sets whether Luau code can mutate this table.
    pub fn set_readonly(&self, enabled: bool) {
        unsafe {
            (*self.table.as_ptr()).readonly = u8::from(enabled);
        }
        if !enabled {
            self.invalidate_safe_env();
        }
    }

    /// Returns whether this table is readonly.
    pub fn is_readonly(&self) -> bool {
        unsafe { (*self.table.as_ptr()).readonly != 0 }
    }

    /// Controls Luau's safe-environment optimization for this table.
    ///
    /// A safe environment permits the VM to cache imported globals and assume
    /// selected builtins have not been replaced. The full lookup graph,
    /// including nested tables and host state observed through callbacks or
    /// metamethods, must remain stable while this is enabled. Mutations
    /// performed by Luau code or outside the safe API cannot be detected;
    /// disable this on the sandbox or function environment before they occur.
    pub fn set_safe_env(&self, enabled: bool) {
        unsafe { (*self.table.as_ptr()).safe_env = u8::from(enabled) };
    }

    /// Returns a pointer that uniquely identifies this table.
    pub fn to_pointer(&self) -> *const () {
        self.pointer()
    }

    pub(crate) fn push_to(&self, target: impl AsRef<VmThread>) -> Result<(), Error> {
        unsafe {
            let target = target.as_ref();
            if !target.same_vm(self.reference.reference_thread()) {
                return Err(Error::foreign_lua_handle());
            }
            target
                .push_table(self.table)
                .map_err(|exit| Error::from_thread_exit(target, exit))
        }
    }

    pub(crate) fn thread(&self) -> Thread<'lua> {
        self.reference.thread()
    }

    pub(crate) fn pointer(&self) -> *const () {
        self.table.as_ptr().cast()
    }

    fn invalidate_safe_env(&self) {
        self.reference.runtime().invalidate_managed_safe_env();
        self.set_safe_env(false);
    }
}

impl PartialEq for Table<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.reference == other.reference
    }
}

impl Eq for Table<'_> {}

impl object::private::Sealed for Table<'_> {}

impl<'lua> ObjectLike<'lua> for Table<'lua> {
    fn get<V>(&self, key: impl IntoLua<'lua>) -> Result<V, Error>
    where
        V: FromLua<'lua>,
    {
        Table::get(self, key)
    }

    fn set(&self, key: impl IntoLua<'lua>, value: impl IntoLua<'lua>) -> Result<(), Error> {
        Table::set(self, key, value)
    }

    fn call<R>(&self, args: impl IntoLuaMulti<'lua>) -> Result<R, Error>
    where
        R: FromLuaMulti<'lua>,
    {
        unsafe {
            let thread = self.thread();
            let vm_thread = thread.as_vm();
            let stack = StackGuard::new(vm_thread);

            self.push_to(&thread)?;
            let arg_count = i32::try_from(args.push_into_stack_multi(&thread)?)
                .map_err(|_| Error::StackError)?;
            vm_thread
                .protected_call(arg_count, LUA_MULTRET, 0)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))?;
            let result_count = vm_thread.get_top() - stack.top();
            R::from_stack_multi(&thread, stack.top(), result_count)
        }
    }

    fn call_method<R>(&self, name: &str, args: impl IntoLuaMulti<'lua>) -> Result<R, Error>
    where
        R: FromLuaMulti<'lua>,
    {
        let function = self.get::<Function<'lua>>(name)?;
        unsafe {
            let thread = self.thread();
            let vm_thread = thread.as_vm();
            let stack = StackGuard::new(vm_thread);

            function.push_to(&thread)?;
            self.push_to(&thread)?;
            let arg_count = args
                .push_into_stack_multi(&thread)?
                .checked_add(1)
                .ok_or(Error::StackError)?;
            let arg_count = i32::try_from(arg_count).map_err(|_| Error::StackError)?;
            vm_thread
                .protected_call(arg_count, LUA_MULTRET, 0)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))?;
            let result_count = vm_thread.get_top() - stack.top();
            R::from_stack_multi(&thread, stack.top(), result_count)
        }
    }

    fn call_function<R>(&self, name: &str, args: impl IntoLuaMulti<'lua>) -> Result<R, Error>
    where
        R: FromLuaMulti<'lua>,
    {
        self.get::<Function<'lua>>(name)?.call(args)
    }

    fn to_string(&self) -> Result<String, Error> {
        unsafe {
            let thread = self.thread();
            let vm_thread = thread.as_vm();
            let _stack = StackGuard::new(vm_thread);
            self.push_to(&thread)?;
            let bytes = vm_thread
                .lua_to_string(-1)
                .map_err(|exit| Error::from_thread_exit(vm_thread, exit))?;
            bytes.to_str().map(str::to_owned).map_err(|error| {
                let message = error.to_string();
                Error::from_lua_conversion("string", "String", Some(message.as_str()))
            })
        }
    }

    fn to_value(&self) -> Result<Value<'lua>, Error> {
        self.try_clone().map(Value::Table)
    }
}

impl<'lua, 'table> IntoLua<'lua> for Table<'table>
where
    'table: 'lua,
{
    fn into_lua(self, _: crate::LuaRef<'lua>) -> Result<Value<'lua>, Error> {
        Ok(Value::Table(self))
    }

    unsafe fn push_into_stack(self, thread: &Thread<'lua>) -> Result<(), Error> {
        self.push_to(thread)
    }
}

impl<'lua, 'table> IntoLua<'lua> for &Table<'table>
where
    'table: 'lua,
{
    fn into_lua(self, _: crate::LuaRef<'lua>) -> Result<Value<'lua>, Error> {
        self.try_clone().map(Value::Table)
    }

    unsafe fn push_into_stack(self, thread: &Thread<'lua>) -> Result<(), Error> {
        self.push_to(thread)
    }
}

impl<'lua> FromLua<'lua> for Table<'lua> {
    fn from_lua(value: Value<'lua>, _: crate::LuaRef<'lua>) -> Result<Self, Error> {
        match value {
            Value::Table(table) => Ok(table),
            value => Err(Error::from_lua_conversion(value.type_name(), "table", None)),
        }
    }
}