How can I check if a function is defined in the chaiscript and how can I execute it with typed arguments?

909 views Asked by At

I just discovered chaiscript and I like it a lot. Now I want to add support for my very simple opengl 3d engine.

I have C++ math-classes: vec2T, vec3T, vec4T, mat2T, mat3T, mat4T, ... (they are actually template classes and there are typedefs that make them vec4i, vec4f, vec4d, ...)

I think I can add them to chaiscript with:

chai.add(chaiscript::user_type<vec4i>(), "vec4i");

right?

Now, I want to test if my script contains a function called "onFrame". If it is, I want it to be called with a vec4i parameter as its first argument. How do I do this?

I understand that I can do something like this:

try
{
    chai("onFrame();");
}
catch (const std::exception &)
{
}

If onFrame is not defined in the script, the exception will be ignored this way. I can even pass some integer or string parameters this way. But how do I go on to pass a vec4(x, y, z, w) parameter to it?

Any help is appreciated!

1

There are 1 answers

2
lefticus On BEST ANSWER

There seems to actually be several questions here.

You can add the type name to ChaiScript with user_type but you will still need to add any of the methods that you want to use.

Since you mention that they are templated types, I would suggest adding a templated function on your side that makes adding each template instantiation you want for you.

Yes, you are correct that catching the exception would silently ignore that a function does not exist. However, in practice if you are literally doing this on every frame your runtime will suffer. It is expensive to throw/catch exceptions.

You have many options for how you might go about passing your vec4i object to the function. Do you want to do it from C++ or inside of ChaiScript for example?

One option is to do it in a strongly typed way from C++

auto func = chai.eval<std::function<void (const vec4i &)>>("onframe");
func(somevector);

I suggest looking over the cheatsheet to see if it answers remaining questions.