Syntax for chaiscript callbacks


I’m not near a computer where I can try this but wanted to ask.

If I have injected a method name and an object instance into chaiscript I know I can write

method(instance, a, b, c)
instance.method(a, b, c)

However, can I define a chaiscript function both these ways? In other words, I know I can write

def method(instance, a, b, c)
// call back into a C++ method on the given instance

but supposing what I need to do is call that method FROM C++ (i.e. , a callback). Do I have to declare the chaiscript function as above or can I also write

def instance.method(a, b, c)
// This can be called from C++

In other words, I’m wondering if the syntax is consistent for both calling and defining functions with instances.



I kind of see two different questions here, first off, these two following things are equiv

def some_string_method(String s, a, b, c) { 

same as:

def String::some_string_method(a, b, c) { 
 // there is an implied "this" object in the function body here

In either case you can make it visible to C++, but you must explicitly pass that back to C++ in the form of an std::function object, there’s now way to implicitly make it available to C++.

void add_callback(cons std::function<void (const std::string &, int, int, int)> &callback)
  // do something with callback

chai.add(chaiscript::fun(&add_callback), "add_callback");

From chaiscript



Thanks - did not realize that syntax was allowed. And yes, I understand I have to insert it into chaiscript with the function syntax, I had been doing that for other non-object stuff already.


Follow on question:

From C++, I can inject method names with parameters (properly typed) and then separately inject a global instance variable, also properly typed.
However, from the Chaiscript side I do not need to specify types to be able to refer to these things.

So given that instances are always pointers under the cover, is there any way for me to define callbacks at the ChaiScript end WITHOUT using specific types?


Without getting really complex, you can make parameters generic by making them chaiscript::Boxed_Value type, but you still need to know the arity of the function.

If you wanted to get really really generic you could make a callback that is something like:

std::function<Boxed_Value (const std::vector<Boxed_Value> &bv)>

If I’m catching your meaning.