lua-users home
lua-l archive

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


Thanks.

Wouldn't it be cheaper & more efficient to use the registry rather than a metatable subtable?

callback(cpp_class *c)
{
      lua_State *L = c->lua();
      lua_pushlightuserdata(L, c);
      lua_gettable(L, LUA_REGISTRYINDEX);
      //either nil or your userdata will no be on the stack
}

If I need to type-check, I can compare the metatable of the userdata to the class name:

bool typecheck(lua_State * L)
{
	lua_getfield(L, LUA_REGISTRYINDEX, c::classname);
	if (lua_getmetatable(L, -1) && lua_rawequal(L, -1, -2))
	{
		lua_pop(L, 2);	// remove both metatables
		return true;
	}
	lua_pop(L, 1);	// remove class table
	return false;
}


On Feb 26, 2007, at 5:23 PM, Wesley Smith wrote:

I think, as suggested by Rici, that you need a table mapping C++
pointers to userdata in the Lua userdata's metatable.  somehow you'll
need to get the lua_State.  In this case, I assume a pointer is cached
in the cpp_class and that the table of cpp pointers to userdata is in
the metatable's "instances" field;

pseudo code

callback(cpp_class *c)
{
   lua_State *L = c->lua();
      luaL_getmetatable(L, cpp_class::metatable_name);
      lua_pushstring(L, "instances");
      lua_gettable(L, -2)
      lua_pushinteger(L, (int)c);
      lua_gettable(L, -2)
      //either nil or your userdata will no be on the stack
}


Also I would make the "instances" table a weak table with __mode = "v"

wes