Reusing ChaiScript class


Hi there, creating a new chaiscript::ChaiScript takes quite a bit of time and I’d like to be able to use the same instance over multiple points in my project. Also having to chai.add() the same things at every point would add a lot of clutter. Now using it in multiple places is not much of a problem except that it seems like when you add a variable then you can not delete it anymore.

So for instance I add a variable containing some text, use that when I evaluate some chai code and finish. Then at some other point I evaluate some chai code, but that variable is still there. How do I undo a chai.add()?


You can create the state that you want, then store the state. After evaluating code, restore the state, which will put the engine back in the state it was prior to the evaluation. After creating your state by doing all of the chai.add() stuff that you want, do something like the following:

// save the state
const auto base_state  = chai.get_state();
const auto base_locals = chai.get_locals();

// evaluate whatever...

// restore the state