How to determine if a custom C ++ type is registered in tolua

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

Suppose I have a C ++ class:

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

and 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 question is:

tolua_pushusertype calls segfault in Lua if the third parameter does not match the valid full C ++ class string that was registered when tolua_cclass was called. So, if parameter 3, where "Bar", we get segfault.

I would like to do 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 any way to do this with tolua?

+4
source share
2 answers

I use tolua, not tolua ++, but I hope this is somehow similar. In tolua, you can check if a class is registered as follows:

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

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

Edited: More curious, I downloaded tolua ++ sources and looked inside. It does not look completely alike, and there is no critical function. I have to give you an unverified suggestion that might work:

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

The difference between tolua and tolua ++ is similar to that tolua uses the "namespace" for its created meta tags (tolua prefix.).

+1
source

I'm just a beginner of lua, so my suggestion is: wrap your tolua calls in your own function that keeps track of the classes registered in it. Now you can ask your wrapper if tolua knows your class.

0
source

Source: https://habr.com/ru/post/1307073/


All Articles