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 508 forks source link

How to use usertypes in lua? #1342

Closed GreedyTactician closed 2 years ago

GreedyTactician commented 2 years ago

I stared at the documentation and the examples for a while and I figured I'd just ask because nothing seems to cover this basic case.

typedef struct
{
    float x;
    float y;
} vec2;

auto test = [](float x, float y)
{
    return vec2{x, y};
};

lua["f"] = test;
lua.script("a = f(2, 3)");

a is now a usertype. How do I access x and y? print(a.x) doesn't work.

Do I need to do shenanigans in C++ with lua.new_usertype<name>?

The documentation says the following

If the type is default_constructible, sol will generate a "new" member on the usertype for you.

But my brain is too smooth to understand the information that follows.

Rochet2 commented 2 years ago

Do I need to do shenanigans in C++ with lua.new_usertype<name>?

Yes, exactly. See the basic tutorial and the rest of the usertype documentation.

There is no reflection in C++, so sol cant really generate code on its own for arbitrary structs and classes with just C++. However, it is possible to hardcode functionality with templates if you know, for example, the function signature beforehand. So sol has hardcoded support for default constructor (and some other things, like to_string).

GreedyTactician commented 2 years ago

Ah, I see. I was hoping to avoid that. Thank you

Rochet2 commented 2 years ago

There are some generators around that can try to read through C++ code and then make the bindings for lua. I know of at least one generator for sol. I think it is this one https://github.com/ObEngine/Obidog Have not tried it though, but looked pretty cool when I was looking for something similar few years back.