Returning multiple objects "by value"

Returning multiple objects "by value"

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:

class_<SomeClass>("SomeClass")

.def(constructor<>())

.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.