传递 C++ 对象,以便 Lua 可以使用它

Pass C++ Object so Lua can use it

我了解 Luabind 我可以公开 类 然后可以在 lua.

中创建那些 类 的实例
module[L_state]
   [
      class_<Player>("Player")
      .def(constructor<>())
      .def("Update",&Player::Update)
   ];

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

但是,如果我想在 C++ 中创建播放器实例怎么办,因为我想在 C++ 中调用它的成员,但我也想将播放器的同一实例公开给 Lua,这样它仍然可以调用它功能如:

player:Update()

您可以通过 luabind 将值压入 Lua 堆栈:

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

一个可运行的例子:travis-ci, source.

P.S。当心对象生命周期和所有权问题。 Lua绑定生命周期策略的 LuaBridge manual can be of help to plan a strategy of shared object lifetime management. + an updated LuaBind manual