Controlling print destination


Is there a way to control how output from print() is handled? For my intended use, stdout is very unfortunate. Ideally I want print() to reach a function of my own, accepting a std::string to output.


The easiest way is to simply create your own global print function. It will take priority over a built in one.


global print = someotherfunction; // assuming someotherfunction is already defined
// this one is fun because it captures the existing print function, then prepends your
// own message to the front and calls the built in `print` to display to stdout
global print = fun[print](x) { print("My Logger: ${x}"); };
// C++
// or you could do it this way, all from C++ land
chai.add_global_const("print", chaiscript::fun(&myoutputfunction));


Thanks Jason. A slight modification seems to do just what I want.

static void print_(const std::string& v) {
std::cout << “" << v << "\n”;

chaiscript::ChaiScript script;
script.add(chaiscript::fun(print_), “print_”);
script(“global print = funprint { print_(”${x}"); };");

I had tried adding a C++ print function accepting const Boxed_Value&, but my attempts to get a string out of whatever type it contained it failed miserably. The double-dispatch via a script function was a neat trick.


I’m glad you found an answer. I lost power at the exact moment I went to sent the following message (which is right up with what you came up with):

My personal choice would be to do a combination, to take advantage of automatic string conversions inside of chaiscript:

// c++
void handle_output(const std::string &t_str) {
  // do someting with t_str, redirect to console or whatever

int main() {
  // make chaiscript, watever
  chai.add(chaiscript::fun(&handle_output), "handle_output");
global print = fun(x){ handle_output(to_string(x)); }


Hello Jason,

The same thing is for the “put” function since it outputs to the stdout. Right? And all other possible future built-in functions that will output to stdout need to be overridden. Right? I think it’s not quite convenient. Probably, it’s a better way to let a programmer to setup ChaiScript engine to redirect all output from it to a custom provided function in C++ code… What do you think? Is it possible to implement it in ChaiScript? Is it hard to implement within the current ChaiScript’s architecture?



Definitely possible to implement. It would just require some extra parameters to be passed to the bootstrap functions to let the user decide what to register.

Patches are welcome