lua-users home
lua-l archive

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

On 3/21/2010 11:12 AM, Mark Hamburg wrote:
I haven't looked at how Lunar builds objects. Maybe it sticks the methods in the metatable and has the metatable point back to itself via the __index entry.
At the risk of embarrassing myself, here's how I *think* lunar works when creating a 'class' called Point. It first creates a metatable called Point, and adds some standard methods to it (__index, __tostring, __gc, new, etc.) It then stores this table in the registry for later use. It is this table to which I added the __mul method. When lunar creates a Point object (using its C++ push method), it creates a userdata representing the object, then assigns it the metatable created earlier. As for __index, here is the most salient bit of lunar code, from the Register function, where all this is set up:

  static void Register(lua_State *L) {
    int methods = lua_gettop(L);

    luaL_newmetatable(L, T::className);
    int metatable = lua_gettop(L);

    // store method table in globals so that
    // scripts can add functions written in Lua.<--- what I want to do!
    lua_pushvalue(L, methods);<--- methods is the index of a new table
    set(L, LUA_GLOBALSINDEX, T::className);<--- Here, className would be Point

    // hide metatable from Lua getmetatable()
    lua_pushvalue(L, methods);
    set(L, metatable, "__metatable");<--- metatable is index of a new metatable

    lua_pushvalue(L, methods);
    set(L, metatable, "__index");

I believe I can entirely explain your initial report based purely on the diagnosis that __mul has been created as a method on the object rather than as an entry in the metatable. Your report that the last construct actually works would suggest that something more subtle was going on in bot:getLoc().

Perhaps the initial report; however, I am pretty sure that _mul has been created on the metatable. This was also suggested by another respondent, after which I tried the code below with the results posted belower (a new word!). My knowledge of Lua is somewhat limited, but I can say with some confidence that _mul is on the metatable and not the table.

So I'm voting for something subtle is going on.


  for k,v in pairs(getmetatable(bot:getLoc())) do

And got this (by the way, __mul & __add are lua funcs, the rest are defined in C++):

lenSquared      function: 01875200
__mul   function: 01877168
distanceTo      function: 01875330
__add   function: 01877198
distSquared     function: 01875298
len     function: 01875258
getxy   function: 018751C0
angleTo function: 018752D8
new     function: 018771C8