Allow user defined type conversions


How might we go about allowing the user to specify a type conversion?

If we do it in a templated way from within C++, like:

chai.add(conversion<FromType, ToType>(...));

We limit the ability to add one from within ChaiScript.

If we do something more generic like:

chai.add(conversion(fromTypeId, toTypeId, conversionFunction));

Where conversionFunction is a function that takes a Boxed_Value and returns a Boxed_Value, we allow the user to specify conversion functions from within ChaiScript, but introduce the possibility of the user creating an infinite loop where one conversion function calls another recursively.

Conversion Operators
Pass array from script to C++ function

I’ve opted for the chaiscript enabled version.

You can call it either via script or via chaiscript.add()


I like this implementation a lot. Would it be possible to pass in c++ “typecast” (single argument) constructors as conversion functions?


Since it’s takes a function, you could do anything you wanted. Taking a C++ example version:

The call to chaiscript::type_conversion registers a C++11 lambda function that performs a conversion based on the Type2(const TestBaseType &) constructor.


@lufinkey FYI, as of the last commit this branch is now actually faster then develop branch.


Awesome. Very nice implementation. Do you know when you plan to merge it with the develop or master branch?


There is currently a crash in gcc 4.6 Debug builds that I need to figure out. Then I’ll get it merged.


@lufinkey The problem is worse than I thought - taking my string -> Type_Info conversion example, if you do that, then do:

if ("string" == "string") it actually converts them to Type_Info objects, then tries to compare the type info objects, instead of just doing the string comparison, the obvious thing.

I need to come up with a better function dispatch to know what is the most appropriate function to call. Unfortunately, that’s pretty risky.

I think there’s a chance I could actually make all function calls faster with the changes I have in mind, but I have to figure it out still.

You’re welcome to use this branch in the meantime, but consider that it might not always call the function you think it should until I get this fixed.


it’s all good. I’m in no rush, and I’ll just work around it for now.


@lufinkey this fixes the last remaining issues I had:

I also added a shortcut for defining type conversions that C++ can do automatically, just to make ChaiScript aware of them. I’d expect this kind of conversion is likely the one that you would want:

m->add(chaiscript::type_conversion<const char *, std::string>());


@lufinkey Man this feature has been hard to get right. I’m getting test failures on almost everything that’s not gcc. It probably won’t work for you yet.


As an FYI to anyone reading this discussion later, the support is fully implemented and available in ChaiScript 5.5.0.