Question

I'm using Luabind to expose my game engine to Lua. I recently ran into trouble when I found out that there is no way for me to create a "new" e.g. GUIObject * obj = new GUIObject() in Lua, instead everything created within Lua is owned by Lua.

Well that wasn't a huge issue I decided to just create a sort of Factory pattern on objects for e.g. my GUIManager Has

class GUIManager {
template <class T> T * CreateObject( T classType )
{
    return new T();
}
}

My Luabind Bindings look like this :

class_<GUIManager>("GUIManager")
         .def("CreateObject", (GUILabel*(GUIManager::*)(GUILabel classType))&GUIManager::CreateObject<GUILabel>)
         .def("CreateObject", (GUIImage*(GUIManager::*)(GUIImage classType))&GUIManager::CreateObject<GUIImage>)

Everything works find in Lua by calling :

testLabel = theGUI:CreateObject(GUILabel())

However I feel this isn't "correct" as I'm essentially creating an object to pass in, I'm sure there is an easier way but all other methods I've tried so far don't agree with either the compiler or Luabind.

Feel free to ask for more info if needed

Thanks

Was it helpful?

Solution

Since your Luabind Bindings are using explicit instantiations of your CreateObject method, you can bind each instance to a different name:

class_<GUIManager>("GUIManager")
         .def("CreateLabel", /*...*/&GUIManager::CreateObject<GUILabel>)
         .def("CreateImage", /*...*/&GUIManager::CreateObject<GUIImage>)

Then, your Lua code could be "simplified" to:

testLabel = theGUI:CreateLabel()

And you shouldn't need a parameter anymore in your factory method.

class GUIManager {
    template <class T> T * CreateObject() { return new T(); }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top