[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: C++ binding
- From: Sean Conner <sean@...>
- Date: Fri, 8 Apr 2011 04:59:38 -0400
It was thus said that the Great Timothée VERROUIL once stated:
>
> Thanks a lot :)
> so I have to implemente __index as a function.
> But how can I do that in C++ ???
Same way you write the routines for the other metatable functions. As a
function, __index (in Lua) will be called with two paramters, the first
being the table (or userdata) and the second being the key. So, a
hypothetical function might look like (and sorry this is in C; I don't use
C++ but you should be able to translate this):
static int foolua___index(lua_State *L)
{
foo_t *foo;
foo = luaL_checkudata(L,1,FOOTYPE);
/*------------------------------------------------
; okay, index is a string. Check what the index is
; and handle appropriately, pushing the appropriate
; values onto the stack.
;--------------------------------------------------*/
if (lua_type(L,2) == LUA_TSTRING)
{
const char *key;
size_t ksize;
key = lua_tolstring(L,2,&ksize);
if (strcmp(key,"myAttribute") == 0)
{
lua_pushnumber(L,foo->myAttribute);
return 1;
}
if (strcmp(key,"myFunction") == 0)
{
lua_pushcfunction(L,foolua_myfunction);
return 1;
}
/* and so on .. */
}
/*---------------------------------------------
; we've got a number as a key
;---------------------------------------------*/
else if (lua_type(L,2) == LUA_TNUMBER)
{
int idx;
idx = lua_tointeger(L,2);
if (idx > foo->maxIndex)
{
lua_pushnil(L);
return 1;
}
lua_pushnumber(L,foo->data[idx]);
return 1;
}
/*--------------------------------------------------
; something else, like a LUA_TTABLE or LUA_TBOOLEAN
; was passed in as the key. If these make sense,
; handle them, otherwise, return nil.
;---------------------------------------------------*/
lua_pushnil(L);
return 1;
}
And when you initialize the metatable:
lua_pushcfunction(L,foolua___index);
lua_setfield(L,-2,"__index");
-spc (Hope this helps)