Query existence of a function


Is there a way (other than by try/catch) to determine that a function has already been injected into a chaiscript interpreter?

So one could write, for example

if (chai.exists(chaiscript::fun([this]....... )
      // Function exists, don't try to inject it again



It’s an open to-do item to make this user friendly.

There is some discussion about possible methods here:

A possible solution until one is implemented in ChaiScript would be:

// in chaiscript
 def function_exists(String name) { return contains(get_function_objects(), fun(elem){ return elem.first == name; }); }

Then in C++ you might do:

auto function_exists = chai.eval<std::function<bool(const std::string &)>>("function_exists");
if (function_exists("no_func_to_find")) {
  // function exists
} else {
  // it doesn't


Interesting — presumably I would have to inject function_exists itself into the script since I can’t assume users will supply it. Also, will that differentiate among overloaded methods?


There’s a separate function “call_exists” where you can pass in a function and set of params, and it can differentiate the overloads.



But that answers (I think) my original question — you’re saying I can just use call_exists, presumably with the same template I used when I added functions to see if they’re in the chaiscript?


No, both of those functions only exist inside of ChaiScript, so you have to go another route, via chaiscript, to get access to them in C++.

It’s a to-do item to make it better, for sure.