LuaBind:如何将特定的类实例绑定到Lua?

Tra*_*isG 9 c++ lua luabind

(旁注:这是游戏编程)

使用LuaBind将整个类绑定到Lua很容易:

class test
{
   test()
   {
      std::cout<<"constructed!"<<std::endl;
   }

   void print()
   {
      std::cout<<"works!"<<std::endl;
   }
}
Run Code Online (Sandbox Code Playgroud)

//别的地方

   module[some_lua_state]
   [
      class_<test>("test")
      .def(constructor<>())
      .def("print",&test::print)
   ];
Run Code Online (Sandbox Code Playgroud)

现在我可以在Lua中创建该类的实例并使用它:

lua_example.lua

foo = test() //will print "constructed!" on the console
foo:print()  //will print "works!" on the console
Run Code Online (Sandbox Code Playgroud)

但是,现在我想将一个特定的测试实例绑定到Lua.这将使我能够将对象传递给Lua,例如Player类的实例,并执行以下操作:

Player:SetPosition(200,300)
Run Code Online (Sandbox Code Playgroud)

而不是采取艰难的方式,并有类似的东西

SetPosition("Player",200,300)
Run Code Online (Sandbox Code Playgroud)

相应的C++ SetPosition函数需要查找std :: map才能找到播放器.

这是否可能,如果是这样,我怎么能在LuaBind中做到这一点?

Nic*_*las 18

您没有将类的实例绑定到Lua.类的实例只是数据,您可以通过常用方式将数据传递给Lua.但是C++对象很特殊; 因为它们是通过Luabind注册的,所以你必须使用Luabind方法将它们提供给Lua脚本.

有几种方法可以为Lua提供数据,Luabind涵盖了所有这些方法.例如,如果你有一个对象x,它是一个向XLuabind注册的类的指针,你有几种方法可以给Lua x.

您可以将值设置x为全局变量.这是通过Luabind的object界面和globals功能完成的:

luabind::globals(L)["NameOfVariable"] = x;
Run Code Online (Sandbox Code Playgroud)

显然,您可以将其放在另一个表中,该表位于另一个表中,可以从全局状态访问.但是你需要确保表格都存在.

将此数据传递给Lua的另一种方法是调用Lua函数并将其作为参数传递.您可以使用该luabind::object接口将函数作为对象,然后使用luabind::call_function它来调用它.然后,您可以将x参数作为参数传递给函数.另外,如果你喜欢的lua_pcall风格的语法,你可以用x一个luabind::object,并将它推入堆栈luabind::object::push.