lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Special thank to Sean Conner.
'luaL_getmetafield' is what I wanted to have :^) 

> Objet : RE: Two indexing methods of a vector. How to ?
> > I wonder "How to index a userdata, and together define methods in the
> > userdata virtual table".

// This is my actual '__index' definition.

static int meta_index(lua_State *L)
{
	Vec4 *v = Vget(L,1);
	int ntype = lua_type(L,2);
	int ch;

	if (ntype==LUA_TSTRING)
	{
		const char *szIndex = lua_tostring(L,2);

		// check to see if the given name exists in the metatable;
		// if so, we return it.  
	      if (luaL_getmetafield(L, 1, szIndex))
			return 1;

		if (strlen(szIndex)!=1) 
			luaL_error(L, "Bad index");

		ch = *szIndex;
	}
	else if (ntype==LUA_TNUMBER)
	{
		ch = (int)lua_tointeger(L,2) + ('x'-1);
	}
	else
		luaL_error(L, "Bad index type");

	switch (ch)
	{
	case 'x': lua_pushnumber(L,v->x); break;
	case 'y': lua_pushnumber(L,v->y); break;
	case 'z': lua_pushnumber(L,v->z); break;
	case 'w': lua_pushnumber(L,v->w); break;
	default:
		luaL_error(L, "Bad index");
	}
	return 1;
}