Returning multiple objects "by value"

Previous Topic Next Topic
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
Report Content as Inappropriate

Returning multiple objects "by value"

Glen F
Hi there, I'm trying to see if there is anything wrong with returning a table of values, where the values are C++ objects (created on the stack -- do they get copied so that Lua "owns" them?).  If they were really referenced on the stack, I'd expect them to be invalid, or for the program to crash, when I use the returned values much later in Lua code.  But all seems to work, with no crashes, no obvious memory leaks after running for many iterations, and the returned objects contain the expected data.

Is this "okay" to do?  (contrived example, but essentially doing the same as my real code)

luabind::object returnObjects()
    luabind::object retTable = luabind::newtable(getLuaInstance());
    for (size_t i = 0; i < 10; ++i) {
        retTable[i+1] = SomeClass("some initialization data", i);
    return retTable;

returnObjects is registered like this:

     def("returnObjects", &returnObjects),
     // ...

SomeClass is registered like this:

     .def(constructor<string, int>())
     // ...

I know I could register SomeClass to be held in a smart pointer, then have returnObjects return an STL vector of them (using the return_stl_iterator policy), but I'd like to understand what is going on with the above code, because as I say, it seems to work fine.

Is there any problem with returning non-primitive objects this way (in a table)?  Is each object copied, so Lua has its own instance?

Instead of a Lua table, first I tried the same returning a vector of SomeClass (not of SomeClass pointers), and using the return_stl_iterator policy, but the objects must have been freed back by the time I was back in Lua-land(?), because iterating over the returned vector in Lua showed the instances contained garbage values.

Is what I'm doing above correct, or is there a better way?


Is your legacy SCM system holding you back? Join Perforce May 7 to find out:
&#149; 3 signs your SCM is hindering your productivity
&#149; Requirements for releasing software faster
&#149; Expert tips and advice for migrating your SCM now
luabind-user mailing list
[hidden email]