Repository navigation
How can I pass a type by value to Lua instead of a constant reference? #276
|
My bindings return |
Replies: 1 comment
|
LuaBridge decides by the C++ return type: .beginClass<Entity>("Entity")
// const& -> Lua gets a const reference to e.position
.addFunction("getPosition", &Entity::getPosition)
// by value -> Lua gets its own copy
.addFunction("getPositionCopy", [](const Entity* e) { return e->getPosition(); })
// works for properties too
.addProperty("position", [](const Entity* e) { return e->getPosition(); })
.endClass()A lambda without a trailing return type deduces If you have many such getters, a small adapter avoids writing a lambda per binding: template <auto Getter> struct ByValue;
template <class C, class R, R (C::*Getter)() const>
struct ByValue<Getter> {
static std::decay_t<R> get(const C* self) { return (self->*Getter)(); }
};
// usage
.addFunction("getPosition", &ByValue<&Entity::getPosition>::get)(I first tried a generic lambda ( I compiled and ran this against current LuaBridge3 ( One related gotcha I hit while testing: in LuaBridge3, |
LuaBridge decides by the C++ return type:
T/const Tare pushed as a copy (Lua lifetime), whileT&/const T&/ pointers are pushed as a reference to the C++ object (C++ lifetime, and read-only forconst). See Passing Objects in the docs. So you need to register something that returnsVector3fby value. The simplest way is a lambda: