luaur-rt 0.1.1

Safe, ergonomic, mlua-style API for luaur (pure-Rust Luau).
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
//! The [`Value`] enum and the stack <-> `Value` bridges.
//!
//! Mirrors `mlua::Value`. Luau (like Lua 5.x without the integer subtype)
//! stores every number as an `f64`; there is no distinct integer tag at the VM
//! level. We therefore reconstruct the [`Value::Integer`] vs [`Value::Number`]
//! distinction on the way out by testing whether the `f64` is an exact,
//! in-range integer — matching mlua's observable behavior closely enough for
//! the high-level API.

use crate::error::Result;
use crate::function::Function;
use crate::state::Lua;
use crate::string::LuaString;
use crate::sys::*;
use crate::table::Table;

/// The integer type exposed by the API. Mirrors `mlua::Integer` (`i64`).
pub type Integer = i64;
/// The float type exposed by the API. Mirrors `mlua::Number` (`f64`).
pub type Number = f64;

/// A dynamically typed Lua value.
///
/// Mirrors `mlua::Value`. Reference-typed variants ([`Value::String`],
/// [`Value::Table`], [`Value::Function`]) carry handles that keep both the
/// value and the VM alive.
#[derive(Clone, Debug)]
pub enum Value {
    /// `nil`.
    Nil,
    /// A boolean.
    Boolean(bool),
    /// An integer (an `f64` that is an exact, in-range whole number).
    Integer(Integer),
    /// A floating-point number.
    Number(Number),
    /// A string.
    String(LuaString),
    /// A table.
    Table(Table),
    /// A function (Lua or Rust).
    Function(Function),
    /// A raw-pointer light userdata. Mirrors `mlua::Value::LightUserData`.
    LightUserData(crate::light_userdata::LightUserData),
    /// A userdata value with typed Rust-side borrowing.
    UserData(crate::userdata::AnyUserData),
    /// A thread (coroutine).
    Thread(crate::thread::Thread),
    /// A Luau vector (3 `f32` components). Mirrors `mlua::Value::Vector`.
    Vector(crate::vector::Vector),
    /// A Luau buffer (mutable, fixed-size byte array). Mirrors
    /// `mlua::Value::Buffer`.
    Buffer(crate::buffer::Buffer),
    /// A boxed Lua/Rust error carried as a first-class value (mirrors
    /// `mlua::Value::Error`). Produced when a Rust error is returned to Lua.
    Error(Box<crate::error::Error>),
}

impl Value {
    /// `Value::Nil`. Mirrors `mlua::Nil`.
    pub const NIL: Value = Value::Nil;

    /// The Lua type name of this value (e.g. `"nil"`, `"number"`, `"table"`).
    pub fn type_name(&self) -> &'static str {
        match self {
            Value::Nil => "nil",
            Value::Boolean(_) => "boolean",
            Value::Integer(_) | Value::Number(_) => "number",
            Value::String(_) => "string",
            Value::Table(_) => "table",
            Value::Function(_) => "function",
            Value::LightUserData(_) => "userdata",
            Value::UserData(_) => "userdata",
            Value::Thread(_) => "thread",
            Value::Vector(_) => "vector",
            Value::Buffer(_) => "buffer",
            Value::Error(_) => "error",
        }
    }

    /// Whether this is an error value.
    pub fn is_error(&self) -> bool {
        matches!(self, Value::Error(_))
    }

    /// View as a reference to the contained error, if any.
    pub fn as_error(&self) -> Option<&crate::error::Error> {
        match self {
            Value::Error(e) => Some(e),
            _ => None,
        }
    }

    /// Whether this is `nil`.
    pub fn is_nil(&self) -> bool {
        matches!(self, Value::Nil)
    }
    /// Whether this is a boolean.
    pub fn is_boolean(&self) -> bool {
        matches!(self, Value::Boolean(_))
    }
    /// Whether this is a number of either subtype.
    pub fn is_number(&self) -> bool {
        matches!(self, Value::Number(_) | Value::Integer(_))
    }
    /// Whether this is the integer subtype.
    pub fn is_integer(&self) -> bool {
        matches!(self, Value::Integer(_))
    }
    /// Whether this is a string.
    pub fn is_string(&self) -> bool {
        matches!(self, Value::String(_))
    }
    /// Whether this is a table.
    pub fn is_table(&self) -> bool {
        matches!(self, Value::Table(_))
    }
    /// Whether this is a function.
    pub fn is_function(&self) -> bool {
        matches!(self, Value::Function(_))
    }

    /// Lua truthiness: everything except `nil` and `false` is truthy.
    pub fn as_boolean(&self) -> Option<bool> {
        match self {
            Value::Boolean(b) => Some(*b),
            _ => None,
        }
    }
    /// View as an integer if it is one.
    pub fn as_integer(&self) -> Option<Integer> {
        match self {
            Value::Integer(i) => Some(*i),
            _ => None,
        }
    }
    /// View as an `f64` if it is a number of either subtype.
    pub fn as_number(&self) -> Option<Number> {
        match self {
            Value::Number(n) => Some(*n),
            Value::Integer(i) => Some(*i as f64),
            _ => None,
        }
    }
    /// View as a string handle.
    pub fn as_string(&self) -> Option<&LuaString> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }
    /// View as a table handle.
    pub fn as_table(&self) -> Option<&Table> {
        match self {
            Value::Table(t) => Some(t),
            _ => None,
        }
    }
    /// View as a function handle.
    pub fn as_function(&self) -> Option<&Function> {
        match self {
            Value::Function(f) => Some(f),
            _ => None,
        }
    }

    /// Whether this is a userdata value.
    pub fn is_userdata(&self) -> bool {
        matches!(self, Value::UserData(_))
    }

    /// View as a userdata handle.
    pub fn as_userdata(&self) -> Option<&crate::userdata::AnyUserData> {
        match self {
            Value::UserData(u) => Some(u),
            _ => None,
        }
    }

    /// Whether this is a thread (coroutine) value.
    pub fn is_thread(&self) -> bool {
        matches!(self, Value::Thread(_))
    }

    /// View as a thread handle.
    pub fn as_thread(&self) -> Option<&crate::thread::Thread> {
        match self {
            Value::Thread(t) => Some(t),
            _ => None,
        }
    }

    /// Whether this is a Luau vector value. Mirrors `mlua::Value::is_vector`.
    pub fn is_vector(&self) -> bool {
        matches!(self, Value::Vector(_))
    }

    /// View as a vector. Mirrors `mlua::Value::as_vector`.
    pub fn as_vector(&self) -> Option<&crate::vector::Vector> {
        match self {
            Value::Vector(v) => Some(v),
            _ => None,
        }
    }

    /// Whether this is a Luau buffer value. Mirrors `mlua::Value::is_buffer`.
    pub fn is_buffer(&self) -> bool {
        matches!(self, Value::Buffer(_))
    }

    /// View as a buffer handle. Mirrors `mlua::Value::as_buffer`.
    pub fn as_buffer(&self) -> Option<&crate::buffer::Buffer> {
        match self {
            Value::Buffer(b) => Some(b),
            _ => None,
        }
    }

    /// View as an `i32` if it is an in-range integer.
    pub fn as_i32(&self) -> Option<i32> {
        self.as_integer().and_then(|i| i32::try_from(i).ok())
    }
    /// View as a `u32` if it is an in-range integer.
    pub fn as_u32(&self) -> Option<u32> {
        self.as_integer().and_then(|i| u32::try_from(i).ok())
    }
    /// View as an `i64` if it is an integer.
    pub fn as_i64(&self) -> Option<i64> {
        self.as_integer()
    }
    /// View as a `u64` if it is an in-range integer.
    pub fn as_u64(&self) -> Option<u64> {
        self.as_integer().and_then(|i| u64::try_from(i).ok())
    }
    /// View as an `isize` if it is an in-range integer.
    pub fn as_isize(&self) -> Option<isize> {
        self.as_integer().and_then(|i| isize::try_from(i).ok())
    }
    /// View as a `usize` if it is an in-range integer.
    pub fn as_usize(&self) -> Option<usize> {
        self.as_integer().and_then(|i| usize::try_from(i).ok())
    }
    /// View as an `f32`.
    pub fn as_f32(&self) -> Option<f32> {
        self.as_number().map(|n| n as f32)
    }
    /// View as an `f64`.
    pub fn as_f64(&self) -> Option<f64> {
        self.as_number()
    }

    /// A raw pointer identifying reference-typed values (tables, functions,
    /// strings, userdata). Returns null for value-typed (nil/bool/number)
    /// values. Mirrors `mlua::Value::to_pointer`.
    pub fn to_pointer(&self) -> *const std::ffi::c_void {
        match self {
            Value::LightUserData(lud) => lud.0 as *const std::ffi::c_void,
            Value::String(s) => s.to_pointer(),
            Value::Table(t) => t.to_pointer(),
            Value::Function(f) => f.to_pointer(),
            Value::UserData(u) => u.to_pointer(),
            Value::Thread(t) => t.to_pointer(),
            // Buffers are GC objects (reference-typed); vectors are inline
            // value types (no pointer identity), matching mlua.
            Value::Buffer(b) => b.to_pointer(),
            _ => core::ptr::null(),
        }
    }

    /// Compare two values for equality honoring `__eq` metamethods.
    /// Mirrors `mlua::Value::equals`.
    pub fn equals(&self, other: &Value) -> Result<bool> {
        // For reference types, route through the VM's `lua_equal` (which runs
        // `__eq`). For value types, structural equality matches Lua semantics.
        match (self, other) {
            (Value::Table(a), Value::Table(b)) => a.equals(b),
            (Value::UserData(a), Value::UserData(b)) => a.equals(b),
            _ => Ok(self == other),
        }
    }

    /// The metatable-aware string form of this value (honors `__tostring`).
    /// Mirrors `mlua::Value::to_string`.
    #[allow(clippy::inherent_to_string_shadow_display)]
    pub fn to_string(&self) -> Result<String> {
        match self {
            Value::Nil => Ok("nil".to_string()),
            Value::Boolean(b) => Ok(b.to_string()),
            Value::Integer(i) => Ok(i.to_string()),
            Value::Number(n) => Ok(crate::value::format_number(*n)),
            Value::Error(e) => Ok(e.to_string()),
            // Vector is an inline value type: format it directly (mlua does the
            // same, via `Vector`'s `Display`).
            Value::Vector(v) => Ok(v.to_string()),
            // Light userdata: format the pointer, matching Lua's `tostring`
            // (`userdata: 0x...`).
            Value::LightUserData(lud) => Ok(format!("userdata: {:p}", lud.0)),
            // Reference types: ask the VM (honors `__tostring`).
            Value::String(s) => s.to_str(),
            other => {
                // Find the owning Lua via the handle and use luaL_tolstring.
                let lua = match other {
                    Value::Table(t) => t.lua(),
                    Value::Function(f) => f.lua(),
                    Value::UserData(u) => u.lua(),
                    Value::Thread(t) => t.lua(),
                    Value::Buffer(b) => b.lua(),
                    _ => unreachable!(),
                };
                lua.value_to_string(other)
            }
        }
    }
}

/// Format an `f64` the way Lua's `tostring` does for the common cases the
/// tests exercise (e.g. `34.59`, integral floats as plain integers).
pub(crate) fn format_number(n: f64) -> String {
    if n.fract() == 0.0 && n.is_finite() && n.abs() < 1e15 {
        format!("{}", n as i64)
    } else {
        // Rust's default float formatting matches Lua's "%.14g" closely enough
        // for the values under test.
        let s = format!("{n}");
        s
    }
}

impl PartialEq for Value {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Value::Nil, Value::Nil) => true,
            (Value::Boolean(a), Value::Boolean(b)) => a == b,
            (Value::LightUserData(a), Value::LightUserData(b)) => a == b,
            // Numbers compare by value across the integer/float subtypes,
            // matching Lua's `==` (1 == 1.0).
            (Value::Integer(a), Value::Integer(b)) => a == b,
            (Value::Number(a), Value::Number(b)) => a == b,
            (Value::Integer(a), Value::Number(b)) | (Value::Number(b), Value::Integer(a)) => {
                (*a as f64) == *b
            }
            (Value::String(a), Value::String(b)) => a == b,
            // Reference types: identity (NOT `__eq`); use `equals` for `__eq`.
            (Value::Table(a), Value::Table(b)) => a.to_pointer() == b.to_pointer(),
            (Value::Function(a), Value::Function(b)) => a.to_pointer() == b.to_pointer(),
            (Value::UserData(a), Value::UserData(b)) => a.to_pointer() == b.to_pointer(),
            (Value::Thread(a), Value::Thread(b)) => a.to_pointer() == b.to_pointer(),
            // Vectors compare component-wise (value type); buffers by object
            // identity (reference type), matching mlua/Luau `==`.
            (Value::Vector(a), Value::Vector(b)) => a == b,
            (Value::Buffer(a), Value::Buffer(b)) => a.to_pointer() == b.to_pointer(),
            (Value::Error(a), Value::Error(b)) => a.to_string() == b.to_string(),
            _ => false,
        }
    }
}

/// True if the `f64` is an exact integer within `i64` range (so it can be
/// presented as [`Value::Integer`]).
fn is_exact_integer(n: f64) -> bool {
    n.fract() == 0.0 && n.is_finite() && n >= i64::MIN as f64 && n <= i64::MAX as f64
}

/// Push a [`Value`] onto the top of the Lua stack.
pub(crate) fn push_value(lua: &Lua, value: &Value) -> Result<()> {
    let state = lua.state();
    unsafe {
        match value {
            Value::Nil => lua_pushnil(state),
            Value::Boolean(b) => lua_pushboolean(state, *b as c_int),
            // Light userdata: push the raw pointer with tag 0.
            Value::LightUserData(lud) => lua_pushlightuserdatatagged(state, lud.0, 0),
            Value::Integer(i) => lua_pushnumber(state, *i as f64),
            Value::Number(n) => lua_pushnumber(state, *n),
            Value::String(s) => s.push_to_stack(),
            Value::Table(t) => t.push_to_stack(),
            Value::Function(f) => f.push_to_stack(),
            Value::UserData(u) => u.push_to_stack(),
            Value::Thread(t) => t.push_to_stack(),
            Value::Buffer(b) => b.push_to_stack(),
            // luaur is a 3-wide vector build; the 4th component is ignored by
            // the VM. Push x/y/z (w = 0).
            Value::Vector(v) => {
                lua_pushvector_lua_state_f32_f32_f32_f32(state, v.x(), v.y(), v.z(), 0.0)
            }
            // An error value pushes as its message string (so Lua code that
            // receives it can `tostring(err)` it). This matches how a Rust
            // callback's `Err` surfaces to Lua as a string error object.
            Value::Error(e) => {
                let msg = e.to_string();
                lua_pushlstring(state, msg.as_ptr() as *const c_char, msg.len());
            }
        }
    }
    Ok(())
}

/// Build a [`Value`] from the value at stack index `idx` (does not pop). For
/// reference types this registers a registry reference.
pub(crate) fn value_from_stack(lua: &Lua, idx: c_int) -> Result<Value> {
    let state = lua.state();
    unsafe {
        let t = lua_type(state, idx);
        let value = match t {
            x if x == ttype::NIL || x == ttype::NONE => Value::Nil,
            x if x == ttype::BOOLEAN => Value::Boolean(lua_toboolean(state, idx) != 0),
            x if x == ttype::LIGHTUSERDATA => {
                let p = lua_tolightuserdata(state, idx);
                Value::LightUserData(crate::light_userdata::LightUserData(p))
            }
            x if x == ttype::NUMBER => {
                let n = lua_tonumberx(state, idx, core::ptr::null_mut());
                if is_exact_integer(n) {
                    Value::Integer(n as i64)
                } else {
                    Value::Number(n)
                }
            }
            x if x == ttype::STRING => {
                lua_pushvalue(state, idx);
                Value::String(LuaString::from_ref(lua.pop_ref()))
            }
            x if x == ttype::TABLE => {
                lua_pushvalue(state, idx);
                Value::Table(Table::from_ref(lua.pop_ref()))
            }
            x if x == ttype::FUNCTION => {
                lua_pushvalue(state, idx);
                Value::Function(Function::from_ref(lua.pop_ref()))
            }
            x if x == ttype::USERDATA => {
                lua_pushvalue(state, idx);
                Value::UserData(crate::userdata::AnyUserData::from_ref(lua.pop_ref()))
            }
            x if x == ttype::THREAD => {
                lua_pushvalue(state, idx);
                Value::Thread(crate::thread::Thread::from_ref(lua.pop_ref()))
            }
            x if x == ttype::VECTOR => {
                // luaur is a 3-wide vector build: read the three components from
                // the inline `TValue` via `lua_tovector`.
                let p = lua_tovector(state, idx);
                if p.is_null() {
                    Value::Nil
                } else {
                    let comps = core::slice::from_raw_parts(p, crate::vector::Vector::SIZE);
                    Value::Vector(crate::vector::Vector::new(comps[0], comps[1], comps[2]))
                }
            }
            x if x == ttype::BUFFER => {
                lua_pushvalue(state, idx);
                Value::Buffer(crate::buffer::Buffer::from_ref(lua.pop_ref()))
            }
            // Any other exotic tags collapse to Nil.
            _ => Value::Nil,
        };
        Ok(value)
    }
}