Reputation: 11
I need help pushing Games Objects created in C++ into our Lua enviroment. this an example of what that would look like we have the following GameObjects being created in C++
class Player
{
public:
Player(std::string pName, int ObjID)
{
this -> name = pName;
this -> objectId = ObjID
}
std::string name;
int objectId;
};
Now our objects are all being created in C++ and we don't want to have constructors for it in our Lua scripts. I'm open to using either sol or LuaBridge, I've researched their examples and they show how to push classes with constructors and pushing functions, but is it possible to push userdata with properties instead of functions? so that in our lua script instead of doing obj:GetName() we can do obj.name
a bit more details of how we're creating objs and hope to push it:
Player* player1 = new Player("Player1", 1)
Player* player2 = new Player("Player2", 2)
Then hopefully we can push these to the environment somehow, thank you for any help!
What i tried with luabridge:
luabridge::getGlobalNamespace(this->lua_state)
.beginClass<GameObject>("GameObject")
.addProperty("Name", &GameObject::Name)
.endClass();
but as I understand this would be if I want to create new classes through Lua, not pushing classes already created. Tried something similar with sol as well.
Upvotes: 0
Views: 389
Reputation: 11
Alrighty so it seems like I was able to figure it out using sol, after some research on the suggestions from the comments. my solution was to make a small wrapper for my gameobjects:
class Lua_GameObject
{
public:
Lua_GameObject(GameObject* obj) {
this -> real_obj = obj;
objects.push_back(this);
}
std::string GetName() const {
auto name_str = this->real_obj->GetName();
int len = strlen(reinterpret_cast<const char*>(name_str));
return std::string(name_str, name_str + len);
}
static std::vector<Lua_GameObject*> ObjectList() {
return Lua_GameObject::objects;
}
private:
GameObject* real_obj;
static std::vector<Lua_GameObject*> objects;
};
after this I use sol in a different file to expose the class and create the objects like this:
// Exposes Lua_Object to the enviroment
this->lua.new_usertype<Lua_GameObject>(
"GameObject",
// No Constructors from lua
sol::no_constructor,
// Name Property
"Name", sol::property(&Lua_GameObject::GetName),
// List of all objects
"ObjectList", &Lua_GameObject::ObjectList
);
now everytime I create a Lua_GameObject it will automatically be added to the list, just need to add a handle to delete them later:
// Creates GameObject
GameObject* obj = new GameObject("ObjName", 123);
//Creates new lua Object which will automatically add it to GameObject:ObjectList()
Lua_GameObject* lua_obj = new Lua_GameObject(obj);
thank you all for your help!
Upvotes: 1