ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.06k stars 493 forks source link

Sometimes the conversion is not perfect. #1503

Open wzhengsen opened 1 year ago

wzhengsen commented 1 year ago

IDE: Visual Studio 2022 sol2: develop branch

The code:

struct Vector1 {
    int x;
    int y;

    Vector1(int x, int y) : x(x), y(y) {
    }
};

struct Vector2 {
    int x;
    int y;
};

template <class Handler>
bool sol_lua_check(sol::types<Vector2>, ::lua_State* L, int index,
     Handler&& handler, sol::stack::record& tracking) {
    // It can pass the type check correctly.
    return sol::stack::check<sol::lua_table>(
         L, index, std::forward<Handler>(handler), tracking);
}

Vector2 sol_lua_get(sol::types<Vector2>, ::lua_State* L, int idx,
     sol::stack::record& tracking) {
    // However, it is not possible to convert the type.
    tracking.use(1);
    sol::table t = sol::table(L, idx);
    return { t["x"].get<int>(), t["y"].get<int>() };
}

int main() {
    sol::state lua;
    lua.open_libraries(sol::lib::base);
    lua.new_usertype<Vector1>(
         "Vector1", sol::constructors<Vector1(int, int)>());

    lua.script(
         "vector1s = { Vector1.new(3, 6), Vector1.new(6, 3) }");
    auto vector1s = lua["vector1s"].get<std::vector<Vector1>>();// Behavior is correct.

    lua.script("vec2 = { x = 3, y = 6 }");
    auto vec2 = lua["vec2"].get<Vector2>();// Behavior is correct.

    lua.script(
         "vector2s = { {x = 3, y = 6}, {x = 6,y = 3} }");
    auto vector2s = lua["vector2s"].get<std::vector<Vector2>>();//error.

    return 0;
}
image