5

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

OpticFroggy
  • 97
  • 2
  • 10
  • if you will pass a pointer you would not need to create object template T * CreateObject( T *classPtr ) {return new T();} allows for: testLabel = theGUI:CreateObject((GUILabel *) NULL); and template void CreateObject( T *&classPtr ) { classPtr = new T(); } for just: theGUI:CreateObject(testLabel); – Fantastory Aug 17 '12 at 16:08
  • Using that method how would I let Lua know which object I am trying to create ? as far as I'm aware I would end up with the same issue I had earlier of it not knowing which of the 2 bound functions to use and raising an error. – OpticFroggy Aug 17 '12 at 16:16

1 Answers1

3

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(); }
};
jxh
  • 69,070
  • 8
  • 110
  • 193