2016-05-09 20 views
-1

どうすればC++関数を呼び出すテーブルの名前を取得できますか?C++ - Lua:呼び出し元テーブル名を取得

ここにはC++ソースコードがあります。オブジェクトをC++マップとluaテーブルに格納する必要があります.C++ map-> firstはluaのテーブルの同じ名前です。

関数を参照してくださいstatic int move_to(lua_State* L)私はその関数を呼び出すluaテーブルを変更する必要があります。ここではTest.cppの

#include <lua.hpp> 
#include <lauxlib.h> 
#include <iostream> 
#include <map> 
#include <string> 

struct Point{ 
    int x=0, y=0; 
}; 

std::map<std::string, Point> points; 

static int move_to(lua_State* L){ 
    int num_args=lua_gettop(L); 
    if(num_args>=2){ 
     int new_x=lua_tonumber(L, 1);//first argument: x. 
     int new_y=lua_tonumber(L, 2);//second argument: y. 
     std::string name=???;//i need to get the name of the lua table who calls this function. 
     lua_getglobal(L, name.c_str()); 
     lua_pushnumber(L, new_x); 
     // modify point in the lua table. 
     lua_setfield(L, -2, "x");// point.x=x 
     lua_pushnumber(L, new_y); 
     lua_setfield(L, -2, "y");// point.x=x 
     // modify point in the c++ map. 
     points.find(name)->second.x=new_x; 
     points.find(name)->second.y=new_y; 
    }; 
    return 0; 
}; 

static int create_point(lua_State* L){ 
    int num_args=lua_gettop(L); 
    if(num_args>=2){ 
     std::string name=lua_tostring(L, 1);//first argument: name. 
     int x=lua_tonumber(L, 2);//second argument: x. 
     int y=lua_tonumber(L, 3);//third argument: y. 
     static const luaL_Reg functions[]={{ "move_to", move_to},{ NULL, NULL }}; 
     lua_createtable(L, 0, 4); 
     luaL_setfuncs(L, functions, 0); 
     lua_pushnumber(L, x); lua_setfield(L, -2, "x");// point.x=x 
     lua_pushnumber(L, y); lua_setfield(L, -2, "y");// point.y=y 
     lua_setglobal(L, name.c_str()); 
     points.insert(std::pair<std::string, Point>(name, Point()));// insert point in the c++ map. 
    }; 
    return 0; 
}; 


int main(){ 
    lua_State * L=luaL_newstate(); 
    luaL_openlibs(L); 
    luaL_loadfile(L, "script.lua"); 
    lua_pushcfunction(L, create_point); lua_setglobal(L, "create_point");//Register create_point to L. 
    lua_call(L, 0, 0); 
    std::cout<<"c++: a.x: "<<points.find("a")->second.x<<", a.y: "<<points.find("a")->second.y<<std::endl; 
    return 0; 
}; 

は、LUAスクリプトです。私はそれを呼び出すテーブルの名前を機能C++で取得できますか

Test.lua

--   name, x, y 
create_point("a", 10, 11) 
print("lua: a.x: " .. a.x .. ", a.y: " .. a.y) 
a.move_to(1,2) 
print("lua: a.x: " .. a.x .. ", a.y: " .. a.y) 
+0

あなたはより具体的に、このコードを持っている、とあなたは結果がされていることを期待し何の問題を記述してください:それ糖衣構文と短い同等です。 – bodangly

+0

私は質問を編集しました。問題がより明確になることを願っています。理解できないことを教えてください。 –

答えて

1

値に名前がないため、テーブルの名前を取得できません。 そのテーブルを最初の引数として渡してください。のように、このポインタはC++にあります。コロンではなく、ドットの使用されている -

a:move_to(1,2) 

注違い:
Luaは簡単にそれを作るために特別な構文を持っています。

a.move_to(a,1,2) 
関連する問題