0

So after struggling a bit, I have decided to give Luabind a try. I'm currently in the process of figuring things out and currently, my biggest problem is returning userdata (class) created by the lua script. This is the example which I'm working with:

class testclass
{
public:
   testclass(const std::string& s) : m_string(s) {}
   void print_string() { std::cout << m_string << "\n"; }

private:
   std::string m_string;
};

This is how I register the class in Lua, using Luabind:

module(L)
[
   class_<testclass>("testclass")
     .def(constructor<const std::string &>())
     .def("print_string", &testclass::print_string)
];

And this is the content of the Lua script:

a = testclass('Class created by Lua')
return a

Calling print_string() on 'a' in Lua works completely fine. However, afterwards, I'm at loss when trying to retrieve 'a' from the lua stack and then utilize it in my C++ program. What I'm trying to do is:

testclass * tmp = (testclass*)lua_touserdata(lua_state, -1);
tmp->print_string();

Apparently, print_string() is truly being called, because I get a newline in my output, however, I'd like tmp->print_string()'s output to be "Class created by Lua". How do I correctly retrieve the userdata (the class) which is being returned from the script?

prkist
  • 431
  • 5
  • 13
  • "print_string() is truly being called". Well, yeah, because you called it. But it's probably being called with a garbage `this` pointer. What's the context for: `lua_touserdata(lua_state, -1)`? You don't show the code that actually executes your sample script. – Mud Jul 11 '15 at 02:35
  • You need to do a few more steps before returning a class from Lua to C++, check the docs: http://blog.nuclex-games.com/tutorials/cxx/luabind-introduction/ – develCuy Jul 12 '15 at 21:23

0 Answers0