Reusing ChaiScript class


#1

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()?


#2

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...
chai.eval_file(path);

// restore the state
chai.set_state(base_state);
chai.set_locals(base_locals);