lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



Hi people of Lua,

I've registered some functions of an stl vector using Luabind the following way without any problems:

    module(g_pLuaState)
    [
        class_<std::vector<Component *>>("ComponentSet")
            .def(constructor<>())
            .def("push_back",&std::vector<Component *>::push_back)
            .def("at",(Component*&(std::vector<Component *>::*)(size_t))&std::vector<Component *>::at)
    ];

    module(g_pLuaState)
    [
        class_<Component>("Component")
            .def(constructor<>())
            .def("GetPtr", &Component::GetPtr)
            .def("Speak", &Component::Speak)
    ];

    module(g_pLuaState)
    [
        class_<Lamp, bases<Component>>("Lamp")
            .def(constructor<>())
    ];

    module(g_pLuaState)
    [
        class_<Relay, bases<Component>>("Relay")
            .def(constructor<>())
    ];

At the Lua repl, I can instance this vector, and add elements to it:

> c = ComponentSet()
> c:push_back(Relay():GetPtr())
> c:push_back(Lamp():GetPtr())

And I can access the contents of the vector:

> print(c:at(0):Speak())
Relay
> print(c:at(1):Speak())
Lamp

However, eventually, the Relay and Lamp objects I created earlier will be garbage collected, since they aren't bound to anything that Lua can see, so if I continue accessing the vector in this way, after about 14 or so accesses, I get the following error message:

> print(c:at(0):Speak())
std::exception: 'Access violation - no RTTI data!'


Naturally, if I do this instead:

> c = ComponentSet()
> r1 = Relay()
> l1 = Lamp()
> c:push_back(r1:GetPtr())
> c:push_back(l1:GetPtr())

This problem doesn't occur.

My question is, is there a way to prevent these vector elements from being garbage collected without having to keep another list of them in lua?

Also, I had to define a GetPtr() function for the Component class which looks like this:

Component * Component::GetPtr() { return this; }

Is there a way I can get to the pointer from Lua without having to create this function?

Just want to finish up by saying Lua and Luabind are awesome, and I am grateful to the authors and maintainers of these tools.

Regards,
Greg Santucci