3

How do you get a reference to a C++ object, from another C++ object, inside a Lua script? I don't really know how to summarize that in words properly, so let me elaborate with a Lua example first:

function doSomething()
    compo = a:getComponent()
    compo:setVariable(0)
end

a is a C++ object, and the function getComponent returns a pointer:

// inside A.h
Component* A::getComponent();

It seems the problem is that getComponent() is passing a copy of the Component object to Lua, instead of a reference. I come across the same problem with every function that returns a pointer, Lua cannot modify the original object.

Object a seems to be working correctly, if I modify a variable from within Lua, it's outcome is mirrored in C++. Both A and component are bound to Lua already, as well as the required methods.

Am I missing something syntactically or is there more to it than that?

I am using luabind, Lua 5.1, and MinGW. Thanks for any help in advance.

EDIT

Here is the luabind code. I summarized it because there's a bunch of other binds that have no relation to the problem:

luabind::class_<A>("A")
    .def("getComponent", &A::getComponent)
Shel Soloa
  • 104
  • 7
  • I don't think you have enough indirection yet, do you? – Richard J. Ross III Mar 17 '13 at 02:59
  • @RichardJ.RossIII I do have a couple levels of indirection, but it appears otherwise cause I was trying to simplify the problem to its bare roots. Unless you meant that my wording was confusing, in that case, my bad, I tend to ramble. – Shel Soloa Mar 17 '13 at 03:15
  • It would help to show the Luabind code for `A`. – Luc Danton Mar 17 '13 at 03:19
  • @LucDanton There you go, I just put it up – Shel Soloa Mar 17 '13 at 03:29
  • "*I come across the same problem with every function that returns a pointer, Lua cannot modify the original object.*" Can you show proof of that? Show [a short, *complete* program that exhibits this behavior.](http://sscce.org) – Nicol Bolas Mar 17 '13 at 04:10

1 Answers1

0

Make a Lua wrapper for the "component" too. Then make a:getComponent() return the Lua object, not a real reference for the C++ object. Add any methods you need on that new wrapper object. If you have more "objects", rinse and repeat.

In short: for every object you want to manipulate from Lua, you will have to create a Lua wrapper. The only way around that is creating extra functions on the top level object, and calling those from Lua (a:setComponentVariable(0) instead of a:getComponent() + compo:setVariable(0)).

kikito
  • 51,734
  • 32
  • 149
  • 189