How to handle multiple scripts / functions


First - thanks again for the example you created for my query below - it has been very helpful indeed.

I want to be able to put two or more functions into the same Chaiscript file and call those functions from different places in my application (i.e. from entirely different classes)

So my “Player” C++ class might call the chai function “SetPlayerAttributes” while my “World” C++ class might call the chai function “CreateTerrain” and my “Game” C++ class might call the chai function “CreateEntities”

Then I can provide a different Chaiscript file for each level - each containing the same functions.

Q. Can I put different functions into a single Chaiscript file, and execute those functions independently form one another?

If I can, how?!



I recommend that you read this other discussion about multiple scripts here: How to manage multiple scripts

But also, know that you can certainly put multiple functions in one script. For a quick example:

// define a couple of functions
  def fun1(i, j) { i+j;}
  def fun2(i, j) { i*j;}

std::function<int (int, int)> f1 = chai.eval<std::function<int (int, int)>>("fun1");
std::function<int (int, int)> f2 = chai.eval<std::function<int (int, int)>>("fun2");

// now do anything you want to with f1 and f2. Pass them to your other objects, whatever


Thanks - I had missed that other thread earlier, I think…

In your example here, you define two functions, fun1 and fun2 in chaiscript.
Then in c++ you create two function ‘pointers’ (not sure if that’s technically the right term) to those functions?
So should that not read

std::function<int (int, int)> f1 = chai.eval<std::function<int (int, int)>>("fun1");

(I hope so, otherwise I am very confused!!)

Again, thanks for you help - I’m struggling because I’m pretty new to C++ and some of the syntax overwhelms me - but I’m getting there!


Yes, you are right - it’s a typo in the name of the function I’m attempting to return. I’ll correct the code.

And no, function pointer is not the right word for it. “function object” is a better phrase. “functor” is another word, but it’s fallen out of popularity lately. A function pointer is a pointer to a memory location where a function resides. This is similar in concept but it’s a wrapper object that contains the smarts to call a function pointer… essentially.

It’s more complex than that, but there’s a good video from CppCon 2015 that describes std::function and its usage. When the video is released on youtube I’ll try to remember to post a link back here to it.


I’m going to try to make ‘functor’ my word of the week - never heard it before!

I’m particularly pleased as, spotting the typo means I must be beginning to understand some of this :wink:


And here’s the video I mentioned: