Double <-> Float conversions


#1

How do I use floats in chaiscript? It seems that chaiscript does not support floating point literals (3.14f), and only doubles. This is fine, but how do I call functions that take floats, rather than doubles?

As it is, I have glm’s vec3 class bound to chaiscript. But, I can’t construct it like this:

var foo = vec3(1.0, 2.0, 3.0);

because chaiscript does not convert those doubles to floats. To construct the object, I have to do this:

var foo = vec3(float(1.0), float(2.0), float(3.0));

Is this intentional? Would be possible to add floating point literals into chaiscript? Thanks :slight_smile:


#2

ChaiScript has actually supported both float literals and automatic conversion between double<->float for quite some time now. Either option should be working for you.

I’d need to see the implementation of your vec3 to have an idea as to why this wouldn’t be working.

jason@jason-VirtualBox:~/ChaiScript-build$ ./chai 
eval> 1.3f
1.3
eval> 3.14f
3.14
eval> def fun_taking_double(double d) { print(d); }
eval> fun_taking_double(3.14f)
3.14
eval> def fun_taking_float(float f) { print("Float: ${f}"); }
eval> fun_taking_float(3.14) 
Float: 3.14
eval> 

-Jason


#3

Just to further test it with > 1 parameter being converted, I did this:

eval> def vec3(float f1, float f2, float f3) { [f1,f2,f3]; }
eval> vec3(1.0,2.0,3.0)
[1, 2, 3]
eval> vec3(1.0,2.0,3.0)[0].type_name()
float
eval> 

Passes doubles in, puts them into a vector of floats and verifies the vector contains floats.

On a side note - using the 1.0f literal float will be more efficient at runtime, compared to a runtime conversion.


#4

Well, the vec3 class is the one from GLM. This is how I add it to chaiscript:

add_class<vec3>(*module, "vec3", {
       constructor<vec3(const float&, const float&, const float&)>(),
       constructor<vec3(const vec3&)>()
   }, {{fun(&vec3::x), "x"}, {fun(&vec3::y), "y"}, {fun(&vec3::z), "z"}}
);

Ok, it seems floating point literals do work. I just have to use 1.0f instead of 1.f.
However, automatic conversion from doubles is seemingly not working. var foo = vec3(1.0, 2.0, 3.0); gives:

Error: "Error with function dispatch with function 'vec3'" With parameters: (const double, const double, const double)

#5

It must be that you are passing const float &, I don’t have the ability to allow for a conversion of an arithmetic type and keep it as a reference.

If you chance that constructor to:

constructor<vec3(float, float, float)>()

I can almost guarantee it will compile fine and work as expected. Also, there’s no reason to pass float by const &. The float is probably actually smaller on the stack than a pointer would be.

-Jason