I somehow thought that I could override the class method in lua so that when I call this function in C ++ it will do what overloaded in lua. I mean for example:
C ++ Class
class Person { public: Person();
Suppose I have this class attached to lua, so in lua I can use an object:
--Lua code p = Person:new() p:shout()
What I'm trying to achieve looks something like this:
Lua file
--luafile.lua p = Person:new() --instantiate --override shout() p.shout = function(self) print("OVERRIDEN!") end
C ++ 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; }
In the above code, you can see that I am trying to override the Person method in lua and expect the overriden method to be called from C ++. However, when I try it, the overriden method fails. What I'm trying to achieve is the overriden method executed in C ++. How do you achieve this?
====================
I thought it could be done, but I'm not sure if this is good. My idea is that the exported class should have a string representing the name of the global variable in lua, which is used to store an instance of this class. Like this:
class Person { public: Person(); string luaVarName;
So, in lua, the object is responsible for implementing shoutScript () and assigns a global var to the object:
--LUA p = Person:new() p.shoutScript = function(self) print("OVERRIDEN") end p.luaVarName = "p"
With the codes above, I can achieve what I want (although I have not tested it). But is there any other, correct way to achieve what I want?
c ++ override methods class lua
Radi
source share