Lua send reference to C++ class to another class
#1 Members - Reputation: 139
Posted 12 September 2011 - 10:00 AM
Thanks in advance.
#2 Members - Reputation: 4604
Posted 12 September 2011 - 11:46 PM
If you have a class that creates an instance of Lua and then you create a new instance of a class inside of Lua, is there a way to return a reference of the new class back to the class that creates the Lua instance? For example, I have a Manager class that manages enemies. The enemies are created via a Lua script. Each time an enemy is created in Lua, the Manager class needs a reference to the new enemy. Is this possible, and does anyone know how to do it?
Thanks in advance.
Yes, you can use lightuserdata in lua to manage a reference to a C/C++ object.
My game: Gnoblins
Developer journal about Gnoblins
Small goodies: Simple alpha transparency in deferred shader
#3 Members - Reputation: 681
Posted 13 September 2011 - 02:59 AM
Right? If not, and enemy is some kind of Lua table, maybe you go wrong.
Then, when your C++ code is creating any Enemy object for Lua, C++ must create Enemy as a user data (not light user data).
Then you create an enemy object and put the pointer to user data.
Now your C++ code has a pointer to the enemy, and Lua is happy to accept the enemy as a user data.
If you want deep understand, you can read the source code of MLuabind (not luabind).
It's much simpler reading than luabind.
You can see how it uses LuaCustomVariable to manage objects.
PS: by setting __GC in the user data meta table, your C++ code can get called when the user data is going to destroy, then you can free the object in __GC handler.
http://www.cpgf.org/
cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.
v1.5.5 was released. Now supports tween and timeline for ease animation.
#4 Members - Reputation: 120
Posted 13 September 2011 - 03:28 AM
It sounds like what you want it a Lua reference [1] yet you have to take into account that this reference by default will keep the object alive.
[1] http://www.lua.org/manual/5.1/manual.html#luaL_ref
#5 Members - Reputation: 139
Posted 13 September 2011 - 08:51 AM
createNew("Enemy")
That way Lua just sends a String to the C++ causing the creation to happen.
Also, every object should have it's own Lua instance correct?
Thanks again,
Kurasu






