Converting from `const Vector` (in script) to `std::vector` (in C++)


#1

Hi,

I have the following:

void processData(const std::vector<int>& data);

...

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

To be able to use the function, I have also registered the vector type with:

chai.add(chaiscript::bootstrap::standard_library::vector_type<std::vector<int>>("StdVectorInt"));

Then, in the script, I can do the following:

auto data = StdVectorInt();
data.push_back(12);
data.push_back(34);
data.push_back(56);
data.push_back(78);
processData(data);

QUESTION: Is there any mechanism so that I could do the following instead?

processData([12, 34, 56, 78]);

I just wondering whether I could overload the processData() function with some kind of const Vector type.

Thanks,

G


EDIT: It seems that this could be as simple as

void processData(const std::vector<chaiscript::Boxed_Value>& data)

However, it feels that I’m dangerously assuming that the internal container type for ChaiScript’s vectors is std::vector. Is there a typedef anywhere to avoid making such assumption? That I have not been able to find.


#2

Strange that the [] doesn’t resolve as a vector. Interested to see why that is. Did you introduce that second processData as an overloaded method?


#3

Hi Rob, thanks for taking your time to reply.

It was not the function overloading that interested me, but the fact that I had to figure out [] in the script was translated in C++. I eventually discovered that it’s a const std::vector<chaiscript::Boxed_Value>& parameter.

The only side question that this arose is whether there is a typedef in ChaiScript to refer to const std::vector<chaiscript::Boxed_Value>& in a more robust way. But it’s a minor concern.

Thanks!


#4

For the sake of marking this as answered, this is how the function was registered:

void processData(const std::vector<int>& data)
{
    for (const auto& value : data)
        std::cout << value << ", ";
    std::cout << std::endl;
}

void processData(const std::vector<chaiscript::Boxed_Value>& data)
{
    for (const auto& value : data)
        std::cout << chaiscript::boxed_cast<int>(value) << ", ";
    std::cout << std::endl;
}

chai.add(chaiscript::fun(static_cast<void (*)(const std::vector<int>&)>(&processData)), "processData");
chai.add(chaiscript::fun(static_cast<void (*)(const std::vector<chaiscript::Boxed_Value>&)>(&processData)), "processData");

chai.add(chaiscript::bootstrap::standard_library::vector_type<std::vector<int>>("StdVectorInt"));

Then, you can do in the script:

auto data = StdVectorInt();
data.push_back(12);
data.push_back(34);
data.push_back(56);
data.push_back(78);
processData(data);

processData([12, 34, 56, 78]);

I hope it helps.