views:

84

answers:

2

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?

A: 

Swig generates lua wrappers from c++ functions, it does not inject lua functions into c++. If GetEnemies1 is a c++ function, called from other c++ functions, monkey patching wont work.

You will have to rewrite your c++ code so that the code which executes GetEnemies1 looks for some sort of callback which you can wrap with swig.

mikerobi
I realise replacing the method in lua using monkey patching will only affect lua code, and that monkeypatching the C++ itself is not possible, but that is my intention. There are certain C++ methods Id like to monkey patch on the lua end to make them nicer, or even just renaming
Tom J Nowell
A: 

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!

egarcia