Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely pass LUA sequences to C++ using Sol2

Tags:

c++

vector

lua

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.

like image 667
Nathan Whitehead Avatar asked Sep 08 '26 00:09

Nathan Whitehead


1 Answers

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.

like image 59
Nathan Whitehead Avatar answered Sep 10 '26 16:09

Nathan Whitehead