I have used SWIG to bind a set of classes to lua. I know C++ itself doesn’t support monkey patching, and I’m not trying to modify my C++ objects, merely their lua representations. The problem comes if I want to start monkey patching the lua tables and objects exported by SWIG, so that I can modify the API presented on the lua side.
e.g. the following lua code:
game.GetEnemies1 = game.GetEnemies2
does not work as expected. The behaviour after that line is still consistent with the original GetEnemies1 not GetEnemies2.
how do I combat this problem?
I’ve successfully monkeypatched lua userdata by adding and replacing existing methods. It involved modifying their metatables.
Here’s a sample of what I had to do in order to add a couple methods to an existing userdata object.
As you can see, instead of modifying the object iself, I had to modify its metatable.
This solution will only work if your userdata objects are set up so their metatables “point to themselves”:
mt.__index = mt.Regards!