czuger
czuger

Reputation: 914

How to determine if a C++ usertype has been registered with tolua

We use tolua++ to generate Lua bindings for C++ classes.

Assume I have a C++ class:

class Foo
{
    //Some methods in Foo, irrelevant to question.
};

and a tolua .pkg file with the following contents

class Foo
{
};

Consider the following function:

void call_some_lua_function(lua_State* luaState)
{
    Foo* myFoo = new Foo();
    tolua_pushusertype(luaState, (void*)myFoo, "Foo"); 

    //More code to actually call Lua, irrelevant to question.   
}

Now, the actual question:

tolua_pushusertype causes a segfault in Lua if the 3rd parameter does not correspond to a valid fully qualified string of a C++ class that was registered with a call to tolua_cclass. So, if parameter 3 where "Bar", we get a segfault.

What I would like to do is the following:

void call_some_lua_function(lua_State* luaState)
{

    //determine if tolua is aware of my type, how to do this?
    //Something like:
    //if(!tolua_iscpptype_registered("Foo"))
    //{
    //   abort gracefully
    //}

    Foo* myFoo = new Foo();
    tolua_pushusertype(luaState, (void*)myFoo, "Foo"); 

    //More code to actually call Lua, irrelevant to question.   
}

Is there a way to do this using tolua?

Upvotes: 4

Views: 941

Answers (2)

u0b34a0f6ae
u0b34a0f6ae

Reputation: 49813

I am using tolua, not tolua++, but let's hope it is somehow similar. In tolua, you can test if the class is registered with it like this:

tolua_getmetatable(L, "ClassName");
if (lua_isnil(L, -1)) {
   // the class wasn't found
}

Hint: check how tolua.cast is implemented and checks its arguments. It takes a type name as string.

Edited: More curious, I downloaded the tolua++ sources and looked inside. It doesn't look completely similar, and the critical function is missing. I have to give you an untested suggestion that might work:

luaL_getmetatable(L, "ClassName");
if (lua_isnil(L, -1)) {
   // the class wasn't found
}

The difference between tolua and tolua++ seems to b that tolua uses a "namespace" for its created metatables ("tolua." prefix).

Upvotes: 1

Peter G.
Peter G.

Reputation: 15124

I am just a lua beginner, hence my suggestion: Wrap your tolua-calls in your own function which keeps track of the classes registered through it. Now you can ask your wrapper if tolua is aware of your class.

Upvotes: 0

Related Questions