lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Greetings,

I'm having trouble understanding metatables for Object Orientated C++ like
classes (note I'm looking at this from the C++ side of things). Luna by
Lenny Palozzi is helpful for version 4, but I can't figure out the changes I
need to make for v5. I can't seem to find any good sample code for v5
metatables.  The manual doesn't seem to be very helpful to me (and it's
probably just me) in respect to metatables.  A sample would be nice,
including how to add events and values.

How do I add members (properties/methods)?
How do I write/receive a index/newindex member?
How do I use set/getmetatable to change the metatable?


I've placed some code below which is derived from the Luna example code. I
hate copying code this closely, but I'm having understanding this.


//The code below doesn't work
//This is what I have so far (it's basically the Luna code with a few
changes)
template <class T>
class Luna
{
public:
    Luna()
    {
        lua_State* L = getLua(); //Get the lua state
        if (L)
            Register(L); //register class
    }

    // register class T
    static void Register(lua_State* L)
    {
        lua_pushcfunction(L, &Luna<T>::constructor);
        lua_setglobal(L, typeid(T).name());
       //I'm not worried about the GC stuff at the moment, the object can
take care of this themselves.
    }
private:
    // member function dispatcher
    static int thunk(lua_State* L)
    {
        int i = static_cast<int>(lua_tonumber(L,-1));
        lua_pushnumber(L, 0);
        lua_gettable(L, 1);
        T* obj = static_cast<T*>(lua_touserdata(L,-1));
        lua_pop(L, 2);
        //???Here I should be calling the getters and setters of the object,
but I don't know how to determine if we are getting/setting yet???
        return 1;
    }
// constructs T objects
    static int constructor(lua_State* L)
    {
        //Create a new object of type T
        T* obj= new T;
        //Create the tables

        lua_newtable(L); // new table object
        lua_pushnumber(L, 0); // userdata obj at index 0
        lua_pushlightuserdata(L, obj); //???This is probably incorrect???
        lua_settable(L, -3);
        char * extractedName;
        //Loop through each float type in the class, and add that member
(should add both the getter and setter)
        int name;
        for (name=0; name < obj->nOfAttribs(P_FLOAT); ++name)
        {
            //Get the name of the function
            extractedName = obj->getAName(P_FLOAT, name);
            //Push that on to the lua stack
            lua_pushstring(L, extractedName);
            lua_pushnumber(L, name);
            lua_pushcclosure(L, &Luna<T>::thunk, 1);
            lua_settable(L, -3);
        }
        return 1;
    }
};

Confused,
Anderson