9

(旁注:这是游戏编程)

使用 LuaBind 将整个类绑定到 Lua 很简单:

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

   void print()
   {
      std::cout<<"works!"<<std::endl;
   }
}

//别的地方

   module[some_lua_state]
   [
      class_<test>("test")
      .def(constructor<>())
      .def("print",&test::print)
   ];

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

lua_example.lua

foo = test() //will print "constructed!" on the console
foo:print()  //will print "works!" on the console

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

Player:SetPosition(200,300)

与其走艰难的路并拥有类似的东西

SetPosition("Player",200,300)

其中相应的 C++ SetPosition 函数需要查找一个 std::map 才能找到播放器。

这甚至可能吗?如果可以,我怎么能在 LuaBind 中做到这一点?

4

1 回答 1

18

You don't bind instances of classes to Lua. Instances of classes are just data, and you can pass data to Lua via the usual means. C++ objects are special though; because they're registered through Luabind, you have to use Luabind methods to provide them to Lua scripts.

There are several ways to give data to Lua, and Luabind covers all of them. For example, if you have an object x, which is a pointer to class X that is registered with Luabind, there are several ways you can give Lua x.

You could set the value of x into a global variable. This is done through Luabind's object interface and the globals function:

luabind::globals(L)["NameOfVariable"] = x;

Obviously, you can put that in another table, which lives in another table, etc, which is accessible from the global state. But you'll need to make sure that the tables all exist.

Another way to pass this data to Lua is to call a Lua function and pass it as a parameter. You can use the luabind::object interface to get a function as an object, then use luabind::call_function to call it. You can then just pass x as a parameter to the function. Alternatively, if you prefer the lua_pcall-style syntax, you can wrap x in a luabind::object and push it into the stack with luabind::object::push.

于 2011-09-20T11:30:31.863 回答