lua-users home
lua-l archive

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


I must be making this harder then it is but I'm not sure how to lay it out.

I have this:

luaL_newmetatable(L, "Vector");

lua_pushliteral(L, "__index");
lua_pushcfunction(L, LuaVectorGet);
lua_settable(L, -3);

lua_pushliteral(L, "__newindex");
lua_pushcfunction(L, LuaVectorSet);
lua_settable(L, -3);

lua_newtable(L);
int nFuncIndex = lua_gettop(L);

lua_pushvalue(L, nFuncIndex);
lua_setfield(L, LUA_GLOBALSINDEX, msc_pType);

lua_newtable(L);
int mt = lua_gettop(L);
lua_pushliteral(L, "__call");
lua_pushcfunction(L, LuaNew);
lua_pushliteral(L, "new");
lua_pushvalue(L, -2);     // duplicate LuaNew
lua_settable(L, nFuncIndex);
lua_settable(L, mt);
lua_setmetatable(L, nFuncIndex);
lua_pop(L, 2);

User data created like so:
float * fUserData = (float *)lua_newuserdata(L, 4 * sizeof(float));
luaL_getmetatable(L, "Vector");
lua_setmetatable(L, -2);
return fUserData;

This gives me the interface:
local v = Vector.new(1,1,1)
local vec = Vector(1,1,2)
local x = vec.x

the problem is when i want a Length() function

if i switch the __index block to:

lua_pushliteral(L, "__index");
lua_newtable(L);
            lua_pushliteral(L, "Length");
            lua_pushcfunction(L, LuaLength);
            lua_settable(L, -3);

            lua_pushliteral(L, "__index");
            lua_pushcfunction(L, LuaGet);
            lua_settable(L, -3);

            lua_pushvalue(L,-1);
            lua_setmetatable(L, -2);
lua_settable(L, nMetatableIndex);

i now get the interface:
vec:Length()

however the vec.x interface is broken since the __index gets the table on the stack not my userdata.

Hopefully that was clear, i appreciate any comments/ help on a fix for this or on better ways to build what I'm trying to do.

-Chris