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.16k stars 504 forks source link

Can't bind union members to usertype #1409

Closed Lifaon closed 2 months ago

Lifaon commented 1 year ago

Greetings,

First of all, I am using these versions, installed via vcpkg:

I seem to have trouble assigning union members to usertypes. The compiler produces an error, suggesting that I might be trying to bind members to an unrelated class. Are "raw" unions simply not a thing in Lua/sol2? I'm sorry if it's stated somewhere, I couldn't find any information about it.

Here is the error message:

It seems like you might have accidentally bound a class type with a member function method that does not correspond to the class. For example, there could be a small type in your new_usertype(...) binding, where you specify one class "T" but then bind member methods from a complete unrelated class. Check things over!

Here is a simple main.cpp to reproduce the issue:

#include <sol/sol.hpp>

struct S {
    int i;
    char c[4];
};

union U {
    int i;
    char c[4];
};

int main()
{
    sol::state lua;

    // Test with struct
    sol::usertype<S> struct_type = lua.new_usertype<S>("S");
    struct_type["i"] = &S::i;
    struct_type["c"] = &S::c;

    // Test with union
    sol::usertype<U> union_type = lua.new_usertype<U>("U");
    union_type["i"] = &U::i; // <--- Compiler error
    union_type["c"] = &U::c; // Never reached
}

Same happens trying directly from the new_usertype() function:

lua.new_usertype<U>("U",
    "i", &U::i,
    "c", &U::c
); // Compiler error

Thanks in advance for the help.