Skip to content

Commit 76a8f8c

Browse files
committed
Add __type to Error's userdata metatable.
Close #585
1 parent 13395e9 commit 76a8f8c

File tree

3 files changed

+21
-6
lines changed

3 files changed

+21
-6
lines changed

src/util/error.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,11 @@ pub(crate) unsafe fn init_error_registry(state: *mut ffi::lua_State) -> Result<(
349349
state,
350350
Some(|state| {
351351
ffi::lua_pushcfunction(state, error_tostring);
352-
rawset_field(state, -2, "__tostring")
352+
ffi::lua_setfield(state, -2, cstr!("__tostring"));
353+
354+
// This is mostly for Luau typeof() function
355+
ffi::lua_pushstring(state, cstr!("error"));
356+
ffi::lua_setfield(state, -2, cstr!("__type"));
353357
}),
354358
)?;
355359

src/util/userdata.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ pub(crate) unsafe fn get_internal_metatable<T: TypeKey>(state: *mut ffi::lua_Sta
4747
// Uses 6 stack spaces and calls checkstack.
4848
pub(crate) unsafe fn init_internal_metatable<T: TypeKey>(
4949
state: *mut ffi::lua_State,
50-
customize_fn: Option<fn(*mut ffi::lua_State) -> Result<()>>,
50+
customize_fn: Option<fn(*mut ffi::lua_State)>,
5151
) -> Result<()> {
5252
check_stack(state, 6)?;
5353

@@ -62,11 +62,11 @@ pub(crate) unsafe fn init_internal_metatable<T: TypeKey>(
6262
ffi::lua_pushboolean(state, 0);
6363
rawset_field(state, -2, "__metatable")?;
6464

65-
if let Some(f) = customize_fn {
66-
f(state)?;
67-
}
68-
6965
protect_lua!(state, 1, 0, |state| {
66+
if let Some(f) = customize_fn {
67+
f(state);
68+
}
69+
7070
ffi::lua_rawsetp(state, ffi::LUA_REGISTRYINDEX, T::type_key());
7171
})?;
7272

tests/luau.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,5 +436,16 @@ fn test_loadstring() -> Result<()> {
436436
Ok(())
437437
}
438438

439+
#[test]
440+
fn test_typeof_error() -> Result<()> {
441+
let lua = Lua::new();
442+
443+
let err = Error::runtime("just a test error");
444+
let res = lua.load("return typeof(...)").call::<String>(err)?;
445+
assert_eq!(res, "error");
446+
447+
Ok(())
448+
}
449+
439450
#[path = "luau/require.rs"]
440451
mod require;

0 commit comments

Comments
 (0)