sol2
sol2 copied to clipboard
Overriding base types?
I'd like to override the base types of Lua (e.g. maybe replacing the integer type with an arbitrary-precision integer, or a string with a custom string class). Is this even possible? I mean, I know I could register a usertype called String or something, but then if I used functions in my Lua code that used that custom type I'd have to do:
local var = func(custom_string("test"))
Or similar. That isn't ideal. I could make conversion transparent, but then if I (say) wanted to expose methods in QString I'd need to write hundreds of lambdas to convert back and forth. Is this just a pipe dream, or is it doable?
Cant comment really on overriding base types.
I'd need to write hundreds of lambdas to convert back and forth
Hmm, I guess you mean that your implementation would be something along the lines of the following?
lua.new_usertype<MyType>("MyType",
"actualFunction1", [](std::string s){ actualFunction1(convert(s)) },
"actualFunction2", [](std::string s){ actualFunction2(convert(s)) },
"actualFunction3", [](std::string s){ actualFunction3(convert(s)) },
);
I think you can make it transparent in an easier way. See these resources, especially the first code example link:
- https://github.com/ThePhD/sol2/blob/develop/examples/source/customization_convert_on_get.cpp
- https://sol2.readthedocs.io/en/latest/tutorial/customization.html
- https://sol2.readthedocs.io/en/latest/api/stack.html#extension-points
@Rochet2 Yep, exactly what I mean. (As an aside, it doesn't appear that Sol plays well with nested STL types like std::set<std::variant<...>>... any advice for handling that? I'm asking because I want to expose a set that only contains two possible types, but I'm honestly unsure how to register variants in Lua. It would seem kinda awkward having to call variant:new(...) or something. I am using string_views, so I don't know if Sol knows how to work with those.)
@Rochet2 As an alternative to customizing via custom converters, could I just "extend" the existing string type? It would be really cool to be able to do "Hi":index_of(...) or something. If not, I can use the resources you listed, but thought I'd ask anyway.
But for "replacing" existing types I'll definitely look into what you said -- it would be nice having an arbitrary-precision integer/real type.
It would be really cool to be able to do
"Hi":index_of(...)or something
You can do it like this
local foo = "A"
function string.foo(s) return s..s end -- dummy example
print(foo:foo())
As an aside, it doesn't appear that Sol plays well with nested STL types like
std::set<std::variant<...>>... any advice for handling that?
I dont really have anything for that. You can usually wrap things into structs for example to avoid issues.