Skip to content

Commit b1e8369

Browse files
committed
Add lua_getmetatablepointer custom helper
1 parent 12e1493 commit b1e8369

File tree

4 files changed

+51
-0
lines changed

4 files changed

+51
-0
lines changed

luau/Custom/src/lextra.cpp

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#include "lua.h"
2+
#include "lapi.h"
3+
#include "lobject.h"
4+
#include "lstate.h"
5+
6+
extern "C" const void* lua_getmetatablepointer(lua_State* L, int objindex)
7+
{
8+
const TValue* obj = luaA_toobject(L, objindex);
9+
if (!obj)
10+
return NULL;
11+
12+
switch (ttype(obj))
13+
{
14+
case LUA_TTABLE:
15+
return hvalue(obj)->metatable;
16+
case LUA_TUSERDATA:
17+
return uvalue(obj)->metatable;
18+
default:
19+
return NULL;
20+
}
21+
}

src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,8 @@ impl Build {
184184
let custom_lib_name = "luaucustom";
185185
config
186186
.clone()
187+
.include(&vm_include_dir)
188+
.include(&vm_source_dir)
187189
.include(&common_include_dir)
188190
.add_files_by_ext(&custom_source_dir, "cpp")
189191
.out_dir(&lib_dir)

testcrate/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
name = "testcrate"
33
version = "0.1.0"
44
authors = ["Aleksandr Orlenko <[email protected]>"]
5+
edition = "2021"
56

67
[build-dependencies.luau0-src]
78
path = ".."

testcrate/src/lib.rs

+27
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ extern "C" {
3333
cont: *const c_void,
3434
);
3535

36+
pub fn lua_createtable(state: *mut c_void, narr: c_int, nrec: c_int);
37+
pub fn lua_setmetatable(state: *mut c_void, index: c_int) -> c_int;
38+
pub fn lua_getmetatable(state: *mut c_void, index: c_int) -> c_int;
39+
pub fn lua_getmetatablepointer(state: *mut c_void, index: c_int) -> *const c_void;
40+
pub fn lua_topointer(state: *mut c_void, index: c_int) -> *const c_void;
41+
3642
pub fn luau_compile(
3743
source: *const c_char,
3844
size: usize,
@@ -112,6 +118,27 @@ fn test_luau() {
112118
}
113119
}
114120

121+
#[test]
122+
fn test_metatablepointer() {
123+
use std::ptr;
124+
unsafe {
125+
let state = luaL_newstate();
126+
assert!(state != ptr::null_mut());
127+
128+
lua_createtable(state, 0, 0);
129+
assert!(lua_getmetatablepointer(state, -1).is_null());
130+
131+
lua_createtable(state, 0, 0);
132+
let mt_ptr1 = lua_topointer(state, -1);
133+
134+
lua_setmetatable(state, -2);
135+
let mt_ptr2 = lua_getmetatablepointer(state, -1);
136+
assert_eq!(mt_ptr1, mt_ptr2);
137+
138+
lua_close(state);
139+
}
140+
}
141+
115142
#[test]
116143
fn test_exceptions() {
117144
use std::{ptr, slice, str};

0 commit comments

Comments
 (0)