jeremyong / Selene

Simple C++11 friendly header-only bindings to Lua
zlib License
813 stars 117 forks source link

How to get C++ "this" address from registered instances in Lua back to C++? #148

Open shohnwal opened 8 years ago

shohnwal commented 8 years ago

Lets say i have a C++ Luainterface class instance that i want to register in Lua: When registering an already created C++ class instance ina Lua via

void Luainterface::registerMyself() {
    this->lua["CPPinterface"].SetObj(
        *this,
        "cpp_dosomething", &Luainterface::cpp_dosometing
        );
}

and working with the object in Lua and i want to pass the class instances address (or pointer) back to C++ so i can access the instace via a converted C++ pointer, how would i do that?

To be more exact, how do i access the "this" element in the (in this example) CPPinterface table so i can pass this address back to C++ and work with it? The other elements (like &Luainterface::cpp_print) are all associated with a string and it's easy to access them, but i can't figure out how to access the "this" element containing the objects address.

So far i've been creating extra class member with a pointer on itself

class Luainterface {
Luainterface() : cpp_thispointer(this) {} //constructor
//other stuff
Luainterface* cpp_thispointer; //class instance member pointing on itself
}

and register it in the SetObj function in addition to the rest

void Luainterface::registerMyself() {
    this->lua["CPPinterface"].SetObj(
        *this,
        "cpp_this", &Luainterface::cpp_thispointer,
        "cpp_dosomething", &Luainterface::cpp_dosometing
        );
}

It works by converting the Lua table element in C++ back to its originaltype

Luainterface* pointer = (Luainterface*)lua["CPPinterface"]["cpp_this"]()

but it's a bit cumbersome to have that extra member element and extra lua function to register and remember. Would it be somehow possible to access the "this" element (used during the objects registration itself as seen in the example above) in Lua so i can send it back to C++ and convert it back to a pointer or address? Or does the "this" element used above not end up in the Lua table at all and we have to do something like extra entries/members, like i have done above?

PS: Thank you for creating Selene, it's quite awesome! :D