3D シーンで、Lua を使用して移動したい位置を持つオブジェクトがあります。
例えば。box.position.x = 10
ボックスにはメタテーブル ("Object") があり、位置 ("Vec") もあります。オブジェクトには__newindex
、__index
C 関数を呼び出すための と がそれぞれ設定されてNewIndexObject
いIndexObject
ます。Vec (NewIndexVec
およびIndexVec
) と同じです。
オブジェクトには ID があるため、シーンに保存されているリストで識別できbox.position
ます。アクセスされたときにすべて問題なく、C 関数 IndexObject が呼び出され、スタックから ID を抽出できます。box.position.x = 10
「NewIndexVec」が実行されたときです。が呼び出され、スタック上の唯一のものは {table, x, 10} であるため、オブジェクトを識別して x 位置を変更する方法はありません。
値をローカル状態にプッシュする方法はありますか? ヘルプ!
更新:コードを可能な限り要約した以下で、すぐに返信していただきありがとうございます。このコードを実行すると動作するように見えますが、行き詰まっているところにコメントがあります。配列の最初のオブジェクトを取得しているだけですが、ID で選択する必要があります。よろしくお願いします
struct Obj
{
std::string id;
int x,y,z;
Obj()
{
x = 10; y = 20; z = 30;
id = "12345";
}
};
//array of external objects
std::vector<Obj> objects;
int NewObject(lua_State * L)
{
Obj obj;
objects.push_back(obj);
lua_newtable(L);
luaL_getmetatable(L, "MT_Object");
lua_setmetatable(L, -2);
lua_pushstring(L, "id");
lua_pushstring(L, obj.id.c_str());
lua_settable(L, 1);
lua_newtable(L);
luaL_getmetatable(L, "MT_Vec");
lua_setmetatable(L, -2);
lua_pushinteger(L, obj.x);
lua_setfield(L, -2, "x");
lua_pushinteger(L, obj.y);
lua_setfield(L, -2, "y");
lua_pushinteger(L, obj.z);
lua_setfield(L, -2, "z");
lua_setfield(L, -2, "position");
return 1;
}
int IndexVec(lua_State * L)
{
// How do I get the correct object so I can pass its value back
Obj &dunnoObj = objects[0];
std::string key = luaL_checkstring(L,-1);
if(key == "x")
lua_pushinteger(L,dunnoObj.x);
else if(key == "y")
lua_pushinteger(L,dunnoObj.y);
else if(key == "z")
lua_pushinteger(L,dunnoObj.z);
return 1;
}
int NewIndexVec(lua_State * L)
{
// How do I know which object's value to update
Obj &dunnoObj = objects[0];
std::string key = luaL_checkstring(L,-2);
int value = luaL_checkinteger(L,-1);
if(key == "x")
dunnoObj.x = value;
else if(key == "y")
dunnoObj.y = value;
else if(key == "z")
dunnoObj.z = value;
return 0;
}
int main()
{
lua_State * L = luaL_newstate();
luaL_openlibs(L);
luaL_Reg objreg[] =
{
{ "new", NewObject },
{ NULL, NULL }
};
luaL_newmetatable(L, "MT_Object");
luaL_register(L, 0, objreg);
lua_setglobal(L, "Object");
luaL_Reg reg[] =
{
{ "__index", IndexVec },
{ "__newindex", NewIndexVec },
{ NULL, NULL }
};
luaL_newmetatable(L, "MT_Vec");
luaL_register(L, 0, reg);
lua_setglobal(L, "Vec");
int res = luaL_dostring(L, "box = Object.new() box.position.x = 1000 print(box.id .. \" , \" ..box.position.x .. \" , \" .. box.position.y .. \" , \" .. box.position.z)");
if(res)
printf("Error: %s\n", lua_tostring(L, -1));
lua_close(L);
return 0;
}