Question

I am using LuaBind to expose c++ classes to Lua scripts. I have ran into a problem with the inability to cast a base class to its derived class. I have a factory class that returns objects of a base type. There are some fields of a type derived from the base type that I am trying to set with these objects. I have boiled down my problem into some test code that can reproduce the issue and explain it clearer.

c++ Class Definitions

class Base {
public:
  virtual void say() { cout << "a" << endl; }
};

class Derived : public Base {
public:
  virtual void say() { cout << "b" << endl; }
};

class TestClass {
public:
  Base *GetBase() { return (Base *)new Derived(); }
  Derived *derivedRef;
};

c++ LuaBind Binding Code

module(L)[
    class_<Base>("Base")
    .def(constructor<>())
    .def("say", &Base::say)];

module(L)[class_<Derived, Base>("Derived")
    .def(constructor<>())
    .def("say", &Derived::say)];

module(L)[class_<TestClass>("TestClass")
    .def(constructor<>())
    .def("GetBase", &TestClass::GetBase)
    .def_readwrite("derivedRef", &TestClass::derivedRef)];

Lua Code

testClass = TestClass()
base = testClass:GetBase()
testClass.derivedRef = base

Error

 occurred executing a LUA script: No matching overload found, candidates: 
 void <unknown>(TestClass&,Derived* const&)

Does anyone know if upcasting is even possible in LuaBind and if so how I should go about it?

Was it helpful?

Solution

After a long process I solved this problem.

First I read here that the version of LuaBind I am running (0.9) should support automatic down/up casting of types when passed into parameters. This showed that it was possible.

I then found out here that there is a special header to include for converting shared pointers (which I realised I was using). The converter that comes with LuaBind only works with boost shared pointers. It was pretty simple to get the source for the boost smart pointer converter and replace every instance of boost:: with std:: and make a few small modifications so it would compile.

I then started getting errors that said

std::runtime_error: 'Trying to use unregistered class'

when I was calling bind methods.

There was a version of a shared pointer converter here but it didn't compile on my machine. I used it as a reference to make another header file which allows LuaBind to bind shared pointers from the standard library.

To make a long story short, include the following two files and automatic up/down casting of shared pointers work when you use the standard library version rather than the boost version.

I am using Xcode 5 with a clang compiler and I haven't tested it with another compiler.

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