Question

(sidenote: This is game programming)

Binding entire classes to Lua using LuaBind is easy:

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

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

//somewhere else

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

Now I can create instances of the class in Lua and use it:

lua_example.lua

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

However, now I'd like to bind a specific instance of test to Lua. This would enable me to pass objects down to Lua, e.g. an instance of the Player-class and do something like:

Player:SetPosition(200,300)

As opposed to going the hard way and having something like

SetPosition("Player",200,300)

where the corresponding C++ SetPosition function needs to look up a std::map to find the player.

Is this even possible and if so, how can I do it in LuaBind?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top