
Extending sol3's implicit type conversion
Many APIs in my game push Vector3
s to and from Lua. It’s such a common operation,
that most of my functions used to look like this:
sol::table add(sol::table tPos) {
Vector3f pos = TableToPos(tPos);
// do something
return PosToTable(pos);
}
One of the benefits of sol is that it is able to bind Lua arguments to C++ function arguments, converting types implicitly. Having to convert from a table to a vector ourselves is quite annoying. It would be much nicer to have sol do it for us. Luckily, sol allows you to customise how types are retrieved and pushed to Lua using Customisation Points.
When trying to convert a type from Lua to C++, sol will call certain templated functions.
We will be customisating sol’s behaviour using a technique called template specialization,
which allows us to specialise a specific instance of the templated functions and structs.
By the end of this article, we’ll be able to use Vector3
directly when using sol,
allowing the above code to be turned into this:
Vector3f add(Vector3f pos) {
// do something
return pos;
}