Controlling print destination


#1

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.


#2

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

Examples:

//chaiscript
global print = someotherfunction; // assuming someotherfunction is already defined
//chaiscript
// 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));

#3

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.


#4

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");
}
//chaiscript
global print = fun(x){ handle_output(to_string(x)); }

#5

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?

Thanks,
Arlen.