(Solved) Re: Checking type of userdata in C++

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

(Solved) Re: Checking type of userdata in C++

Zé Pedro
Hi thanks for the replies. I've just implemented a solution based on Rici code. The problem was simpler than is seemed. I just had to add the "__typename" field in every metatable created. Then, in the methods where I need to check the datatype, I just push the field __typename and read it.
Thanks again for the help.

José Tavares

On 2/2/07, Rici Lake <[hidden email]> wrote:

On 2-Feb-07, at 4:18 PM, Sam Roberts wrote:

> It looks like in lua 5.0.2, luaL_newmetatable put two entries in the
> registry, one to map the tname to the metadata, and the other to map
> the
> metadata to the tname. So this would be easier if you aren't using 5.1.

Well, that's true enough but lauxlib is not really part of core Lua.

Even if you can't control the creation of metatables, you can certainly
get at them with luaL_newmetatable, so as long as you have a list of
the types you're interested in (which seems a reasonable assumption),
you can do something like this:

static const char* typenames[] = {
   "Zara.Sound",
   "Zara.Sight",
   " Zara.Smell",
   NULL
};

static void identify (lua_State *L, const char* names[]) {
   int i;
   for (i = 0; names[i]; ++i) {
     if (luaL_newmetatable(L, names[i])) {
       luaL_error(L, "Couldn't find the metatable for '%s'", names[i]);
     }
     lua_pushstring(L, names[i]);
     lua_setfield(L, -2, "__typename");
     lua_pop(L, 1);
   }
}

I put a fully functional but useless example at
http://primero.ricilake.net/lua/zara.c




--
Believe nothing, no matter where you read it, or who said it,
no matter if I have said it, unless it agrees with your own reason
and your common sense.
- Buda

Para quê ter olhos azuis, se a Natureza deixa os meus  vermelhos?
- Bob Marley

"Don't try to use what you learn from Buddhism to be a Buddhist;
use it to be a better whatever-you-already-are."
- His Holiness the 14th Dalai Lama

Idealism is what precedes experience; cynicism is what follows.
  - David T. Wolf

"Please don't download, because I want to get a pool in my second home."
  - Kanye West