Pseudo Associative

Random thoughts on software development

2 notes

devbug asked: Hey,

I was using "Wrapping C++ classes in Lua" article, as a guide to expose my C++ classes to Lua but I've encountered an error. I can't seem to get Lua -> C++ calls working. Checking the self argument isn't working; the check function failed. It expects the 'global' metatable (as in the registration of the class) but, gets a table. I know you commented that the code my not be correct however, I've been trying to figure out this issue for a day now. Some help would be greatly appreciated.

Regards,
Mike

Which approach are you using? The one without support for inheritance or the one with support for inheritance which uses the “__self” field on the table? 

In the latter case, there might be a bug in the checkSprite() function. You could try to add this function:

/*! Pops user data of the stack and checks that it is of correct type */

void *popUserData (lua_State *L, int argnum, const char *tname) {

  void *p = lua_touserdata(L, -1);

  if (p != 0) {  /* value is a userdata? */

   if (lua_getmetatable(L, -1)) {  /* does it have a metatable? */

     lua_getfield(L, LUA_REGISTRYINDEX, tname);  /* get correct metatable */

     if (lua_rawequal(L, -1, -2)) {  /* does it have the correct mt? */

       lua_pop(L, 3);  /* remove both metatables  and user data*/

       return p;

     }

   }

  }

  luaL_typerror(L, argnum, tname);  /* else error */

  return 0/* to avoid warnings */

}

And replace the call

ud = luaL_checkudata(L, index, “Lusion.Sprite”);

with 

ud = popUserData(L, index, “Lusion.Sprite”);

Why so complicated you might ask. The problem is that the regular checkudata() function doesn’t deal with the fact that we are using the “__self” variable.

But as mentioned in an answer on the loadcode blog, I think this approach with “__self” got too complicated relative to the benefit. I recommend doing the implementation without inheritance. You will find that given Luas duck typing it is less of a restriction than you think. When I got more time I will write more about this.

  1. assoc posted this