title: Overriding c++ method in lua and call it back in c++
body: <p>I once have thought that I can override a class method in lua so that when I call that function in C++, it will do what has overriden in lua. I mean, like this :</p>
  
  <p><strong>C++ class</strong></p>
  
  <pre><code>
  class Person {
  public:
    Person(); // ctr
    virtual void shout(); // Meant to be overriden
  };
  </code></pre>
  
  <p>Assume that I have that class binded to lua so that in lua, I can use the object :</p>
  
  <pre><code>
  --Lua code
  p = Person:new()
  p:shout()
  </code></pre>
  
  <p>What I'm trying to achieve is something like this :</p>
  
  <p><strong>Lua file</strong></p>
  
  <pre><code>
  --luafile.lua
  p = Person:new() --instantiate
  
  --override shout()
  p.shout = function(self) print("OVERRIDEN!") end
  </code></pre>
  
  <p><strong>C++ code</strong></p>
  
  <pre><code>
  int main() {
    lua_State* l = lua_open();
    luaL_loadlibs(l);
    bind_person_class(l);
  
    luaL_dofile("luafile.lua");
    Person* p = (Person*) get_userdata_in_global(l, "p"); // get the created person in lua
    p->shout(); // expecting "OVERRIDEN" to be printed on screen
  
    lua_close(l);
    return 0;
  }
  </code></pre>
  
  <p>In the code above, you can see that I'm trying to override the Person's method in lua and expect the overriden method to be called from c++. However, when i try it, the overriden method is not executed. What I'm trying to achieve is the overriden method is executed in C++. How do you achieve this?</p>
  
  <p>===================</p>
  
  <p>I've thought a way to achieve this, but I'm not sure if this is good. My idea is the exported class should have a string representing the global variable name in lua that is used to hold the instance of this class. Like this:</p>
  
  <pre><code>
  class Person {
  public:
    Person();
    string luaVarName; // lua's global variable to hold this class
    virtual void shout() { 
      luaL_dostring(luaVarName + ":shoutScript()"); // now shout will call shoutScript() in lua
    }
  };
  </code></pre>
  
  <p>So, in lua, the object is responsible to implement shoutScript() and assign global var to object :</p>
  
  <pre><code>
  --LUA
  p = Person:new()
  p.shoutScript = function(self) print("OVERRIDEN") end
  p.luaVarName = "p"
  </code></pre>
  
  <p>With codes above, I can achieve what I want (haven't tested it, though). But, <strong>is there any other, proper way to achieve what I want?</strong></p>