Skip to content

Commit

Permalink
Add lua_getmetatablepointer custom helper
Browse files Browse the repository at this point in the history
  • Loading branch information
khvzak committed Oct 12, 2024
1 parent 12e1493 commit b1e8369
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
21 changes: 21 additions & 0 deletions luau/Custom/src/lextra.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include "lua.h"
#include "lapi.h"
#include "lobject.h"
#include "lstate.h"

extern "C" const void* lua_getmetatablepointer(lua_State* L, int objindex)
{
const TValue* obj = luaA_toobject(L, objindex);
if (!obj)
return NULL;

switch (ttype(obj))
{
case LUA_TTABLE:
return hvalue(obj)->metatable;
case LUA_TUSERDATA:
return uvalue(obj)->metatable;
default:
return NULL;
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ impl Build {
let custom_lib_name = "luaucustom";
config
.clone()
.include(&vm_include_dir)
.include(&vm_source_dir)
.include(&common_include_dir)
.add_files_by_ext(&custom_source_dir, "cpp")
.out_dir(&lib_dir)
Expand Down
1 change: 1 addition & 0 deletions testcrate/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
name = "testcrate"
version = "0.1.0"
authors = ["Aleksandr Orlenko <[email protected]>"]
edition = "2021"

[build-dependencies.luau0-src]
path = ".."
27 changes: 27 additions & 0 deletions testcrate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ extern "C" {
cont: *const c_void,
);

pub fn lua_createtable(state: *mut c_void, narr: c_int, nrec: c_int);
pub fn lua_setmetatable(state: *mut c_void, index: c_int) -> c_int;
pub fn lua_getmetatable(state: *mut c_void, index: c_int) -> c_int;
pub fn lua_getmetatablepointer(state: *mut c_void, index: c_int) -> *const c_void;
pub fn lua_topointer(state: *mut c_void, index: c_int) -> *const c_void;

pub fn luau_compile(
source: *const c_char,
size: usize,
Expand Down Expand Up @@ -112,6 +118,27 @@ fn test_luau() {
}
}

#[test]
fn test_metatablepointer() {
use std::ptr;
unsafe {
let state = luaL_newstate();
assert!(state != ptr::null_mut());

lua_createtable(state, 0, 0);
assert!(lua_getmetatablepointer(state, -1).is_null());

lua_createtable(state, 0, 0);
let mt_ptr1 = lua_topointer(state, -1);

lua_setmetatable(state, -2);
let mt_ptr2 = lua_getmetatablepointer(state, -1);
assert_eq!(mt_ptr1, mt_ptr2);

lua_close(state);
}
}

#[test]
fn test_exceptions() {
use std::{ptr, slice, str};
Expand Down

0 comments on commit b1e8369

Please sign in to comment.