title: Self pointer, in C++ function from Lua
body: <p>I'm still very new to Lua and I have a hard time trying to figure out the best approach when registering C functions in Lua, but from a C++ class, when it comes to retrieving the self pointer from an object that was <strong>not</strong> created from Lua.</p>
  
  <hr>
  
  <p>Consider the following code:</p>
  
  <h3>foo.h</h3>
  
  <pre><code>class Foo
  {
  public:
      static int lua_DoSomething(lua_State* pState);
      void DoSomething();
  };
  </code></pre>
  
  <h3>foo.cpp</h3>
  
  <pre><code>static const luaL_Reg methods[] =
  {
      {"DoSomething", Foo::lua_DoSomething},
      {nullptr, nullptr}
  };
  
  extern "C"
  {
      int luaopen_Foo(lua_State* pState)
      {
          luaL_register(pState, "Foo", methods);
          return 1;
      }
  }
  
  int Foo::lua_DoSomething(lua_State* pState)
  {
      Foo* self = ???; //&lt;-- how to get self pointer here?
      self-&gt;DoSomething();
      return 0;
  }
  
  void Foo::DoSomething()
  {
      //...
  }
  </code></pre>
  
  <h3>script.lua</h3>
  
  <pre><code>Foo.DoSomething();
  </code></pre>
  
  <hr>
  
  <p>So I got the function registered just fine and <code>Foo::lua_DoSomething</code> gets called (yay!).</p>
  
  <p>However, since the <code>Foo</code> object is <strong>not</strong> created from Lua, how would I go to get the self pointer in function <code>Foo::lua_DoSomething</code>?</p>
  
  <p>Do I have to register some kind of <code>Foo::GetInstance</code> function to Lua, to get the <code>Foo</code> pointer, and then use it in the Lua script somehow?</p>
  
  <p>And what if there's multiple instance of <code>Foo</code>?</p>
  
  <p>What's the cleanest general approach for objects <strong>not</strong> created from Lua?</p>
  
  <p>Thanks!</p>