Patryk
Patryk

Reputation: 24092

How to check if parameter passed to Lua is of user defined type?

I am implementing scripting for my Ogre3d based application using Lua and I have encountered a problem with checking whether a parameter fed into function is of particular type - Ogre::SceneNode*. Anybody knows how can I do it ?

There are some basic Lua functions doing this for built in types like int or string e.g.

if(lua_isnumber(L,1)) {...}

but I do not know how to do it with user defined types.

Upvotes: 1

Views: 2436

Answers (2)

Doug Currie
Doug Currie

Reputation: 41180

If you arrange for each of your userdata of a particular type to share a metatable, then you can use luaL_checkudata to confirm their type. This is typically how a library tags and identifies the data it creates.

Here are some functions that create and check userdata using this technique:

static decContext *ldn_check_context (lua_State *L, int index)
{
    decContext *dc = (decContext *)luaL_checkudata (L, index, dn_context_meta);
    if (dc == NULL) luaL_argerror (L, index, "decNumber bad context");
    return dc; /* leaves context on Lua stack */
}

static decContext *ldn_make_context (lua_State *L)
{
    decContext *dc = (decContext *)lua_newuserdata(L, sizeof(decContext));
    luaL_getmetatable (L, dn_context_meta);
    lua_setmetatable (L, -2); /* set metatable */
    return dc;  /* leaves context on Lua stack */
}

The metatable was created with

const char *dn_context_meta = "decNumber_CoNTeXT_MeTA";
luaL_newmetatable (L, dn_context_meta);

Upvotes: 2

user703016
user703016

Reputation: 37955

I guess lua_isuserdata(L, yourParam) ?

Would be logical.

Upvotes: 1

Related Questions