I have the following classes in C++
class B;
class A {
B* GetB();
void SetB(B*& b) { _b = b;};
private:
B* _b;
}
And part of the lua binding code:
int A::setB(lua_State* L) {
A* a = checkA(L,1) // Macro for luaL_checkudata
B* b = checkB(L,2) // again similar macro
a->SetB(b);
return 0;
}
int A::getB(lua_State* L) {
A* a = checkA(L,1) // Macro for luaL_checkudata
B* b = a->GetB();
// how do i return the already created userdata for this B* instance?
// right now I am doing
B** bp = (B**)lua_newuserdata(L, sizeof(B*));
*bp = b;
luaL_getmetatable(L, "B");
lua_setmettable(L, -2);
return 1;
}
And I want to wrap these as userdata in Lua so I could do something like:
local a = a.new() -- create new userdata
local b = b.new() -- create new userdata
a:SetB(b) -- associate B with A
local b2 = a:GetB() -- get the B associated with A back, and stored as b2
When I print the addresses of b
and b2
I get two unique address, which makes sense because I have called lua_newuserdata
. But ideally I would want it to return the same userdata because they point to the same memory block. How would one do this?
I want Lua to be in 'charge' of the memory, so it will get properly deleted on garbage collection. So I don't know if light userdata is possible.