user441521
user441521

Reputation: 6998

Pass C++ Object so Lua can use it

I understand with Luabind that I can expose classes and then instances of those classes can be created in lua.

module[L_state]
   [
      class_<Player>("Player")
      .def(constructor<>())
      .def("Update",&Player::Update)
   ];

test.lua
player = Player()
player:Update()

But what if I wanted to create that player instance in C++ because I want to call it's members in C++, but I also want to expose that same instance of player to Lua so it can still call it's functions like:

player:Update()

Upvotes: 4

Views: 169

Answers (1)

Dmitry Ledentsov
Dmitry Ledentsov

Reputation: 3660

You can push the value onto the Lua stack via luabind:

Player p;
luabind::globals(L)["player"] = p;

a runnable example: travis-ci, source.

P.S. beware of object lifetime and ownership issues. The LuaBridge manual can be of help to plan a strategy of shared object lifetime management. + an updated LuaBind manual for the LuaBind lifetime policies.

Upvotes: 2

Related Questions