title: C++ - Lua: get caller table name
body: <p>How can i get in a c++ function the name of the table who calls it?</p>
  
  <p>Here is the c++ sourcecode, i need to store objects in a c++ map and in lua tables, the c++ map->first is the same name of the table in lua.</p>
  
  <p>see the function <code>static int move_to(lua_State* L)</code> i need to modify the lua table who calls that function.</p>
  
  <p><strong>Test.cpp</strong></p>
  
  <pre><code>#include &lt;lua.hpp&gt;
  #include &lt;lauxlib.h&gt;
  #include &lt;iostream&gt;
  #include &lt;map&gt;
  #include &lt;string&gt;
  
  struct Point{
      int x=0, y=0;
  };
  
  std::map&lt;std::string, Point&gt; points;
  
  static int move_to(lua_State* L){
      int num_args=lua_gettop(L);
      if(num_args&gt;=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)-&gt;second.x=new_x;
          points.find(name)-&gt;second.y=new_y;
      };
      return 0;
  };
  
  static int create_point(lua_State* L){
      int num_args=lua_gettop(L);
      if(num_args&gt;=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&lt;std::string, Point&gt;(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&lt;&lt;"c++: a.x: "&lt;&lt;points.find("a")-&gt;second.x&lt;&lt;", a.y: "&lt;&lt;points.find("a")-&gt;second.y&lt;&lt;std::endl;
      return 0;
  };
  </code></pre>
  
  <p>Here is the lua script.</p>
  
  <p><strong>Test.lua</strong></p>
  
  <pre><code>--           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)
  </code></pre>