I am using Sol2 to bridge between Lua and C++ code. I would like to pass sequences of numbers from Lua to C++.
From Lua:
func{3, 2, 1.5, 10}
In C++:
void func(std::vector<double> v)
{ ... }
What is the best way to connect the call with the C++ function?
If I directly bind the C++ function I get a segfault. I think I can write a function that converts a sol::table to a std::vector<double>, throwing exceptions if there are any mismatched types, but I'm not sure the best way to do this or if this is the right direction to go.
Here is one solution:
/**
* Convert a Lua sequence into a C++ vector
* Throw exception on errors or wrong types
*/
template <typename elementType>
std::vector<elementType> convert_sequence(sol::table t)
{
std::size_t sz = t.size();
std::vector<elementType> res(sz);
for (int i = 1; i <= sz; i++) {
res[i - 1] = t[i];
}
return res;
}
This manually converts the sol::table into a std::vector and copies each element one by one. It errors if any elements in the table have the wrong type, or if things are missing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With