I am looking for a way to transfer the variable addresses back and forth between C++ and Lua. For instance, transferring an object from C++ to Lua and do some processing, then transfer it back to C++.
However, the thing is how can you execute a C++ functions or methods from Lua? Or is a workaround required?
If possible, could you include a code snippet to show me how it is done?
I am aware that I do not fully understand the whole picture yet, so if something is amiss, please correct me.
It took me a lot of fiddling around to get Lua to work well with C++ classes. Lua is much more of a C style API than C++ but there are plenty of ways to use it with C++.
In the Lua C API a pointer is represented by userdata (or light userdata which have no metatables and are not garbage collected). Userdata can be associated with a metatable which will act a bit like a class in Lua. The C functions that are a part of that metatable wrap the c++ class’s methods and act as the class’s methods in Lua.
Consider a basic person class with private members name (a c string) and age (an int). Name is set by the constructor and can not change. Age is exposed with a getter and setter:
To expose this to Lua first I will write wrapper functions for all of the methods that conform to the lua_CFunction prototype which takes the lua state as an argument and returns an int for the number of values it pushed on to the stack (usually one or zero).
The trickiest of these functions is the constructor which will return a Lua table which acts like an object. To do this lua_newuserdata is used to create a pointer to the pointer to the object. I will assume that we are going to create a meta table "Person" during the Lua init which contain these c functions. This meta table must be associated with the userdata in the constructor.
When the other methods are created, you just have to remember that the first argument will always be the pointer to the pointer we created with newPerson. To get the C++ object from that we just de-reference the return from lua_touserdata(L, 1);.
Finally the Person meta table is set up using luaL_register during the initializing of Lua.
and to test it…
There are other ways to implement OO in Lua. This article covers alternatives:
http://loadcode.blogspot.com/2007/02/wrapping-c-classes-in-lua.html