// https://github.com/kunitoki/LuaBridge3 // Copyright 2023, kunitoki // SPDX-License-Identifier: MIT #include "TestBase.h" #include #include #include #include #include struct ClassExtensibleTests : TestBase { template T variable(const std::string& name) { runLua("result = " + name); return result(); } }; namespace { struct OverridableX { OverridableX() = default; luabridge::LuaRef indexMetaMethod(const luabridge::LuaRef& key, lua_State* L); luabridge::LuaRef newIndexMetaMethod(const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State* L); std::unordered_map data; }; luabridge::LuaRef indexMetaMethodFunction(OverridableX& x, const luabridge::LuaRef& key, lua_State* L) { if (key.tostring() == "xyz") { if (!luabridge::push(L, "123")) lua_pushnil(L); } else { auto it = x.data.find(key); if (it != x.data.end()) return it->second; lua_pushnil(L); } return luabridge::LuaRef::fromStack(L); } luabridge::LuaRef OverridableX::indexMetaMethod(const luabridge::LuaRef& key, lua_State* L) { return indexMetaMethodFunction(*this, key, L); } luabridge::LuaRef newIndexMetaMethodFunction(OverridableX& x, const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State* L) { x.data.emplace(std::make_pair(key, value)); return value; } luabridge::LuaRef OverridableX::newIndexMetaMethod(const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State* L) { return newIndexMetaMethodFunction(*this, key, value, L); } } // namespace TEST_F(ClassExtensibleTests, IndexFallbackMetaMethodMemberFptr) { luabridge::getGlobalNamespace(L) .beginClass("X") .addIndexMetaMethod(&OverridableX::indexMetaMethod) .endClass(); OverridableX x; luabridge::setGlobal(L, &x, "x"); runLua("result = x.xyz"); ASSERT_EQ("123", result()); } TEST_F(ClassExtensibleTests, IndexFallbackMetaMethodFunctionPtr) { luabridge::getGlobalNamespace(L) .beginClass("X") .addIndexMetaMethod(&indexMetaMethodFunction) .endClass(); OverridableX x; luabridge::setGlobal(L, &x, "x"); runLua("result = x.xyz"); ASSERT_EQ("123", result()); } TEST_F(ClassExtensibleTests, IndexFallbackMetaMethodFreeFunctor) { std::string capture = "123"; auto indexMetaMethod = [&capture](OverridableX&, luabridge::LuaRef key, lua_State* L) -> luabridge::LuaRef { if (key.tostring() == "xyz") { if (!luabridge::push(L, capture + "123")) lua_pushnil(L); } else { if (!luabridge::push(L, 456)) lua_pushnil(L); } return luabridge::LuaRef::fromStack(L); }; luabridge::getGlobalNamespace(L) .beginClass("X") .addIndexMetaMethod(indexMetaMethod) .endClass(); OverridableX x; luabridge::setGlobal(L, &x, "x"); runLua("result = x.xyz"); ASSERT_EQ("123123", result()); } TEST_F(ClassExtensibleTests, IndexFallbackMetaMethodFreeFunctorOnClass) { auto indexMetaMethod = [&](OverridableX& x, const luabridge::LuaRef& key, lua_State* L) -> luabridge::LuaRef { auto it = x.data.find(key); if (it != x.data.end()) return it->second; return luabridge::LuaRef(L); }; auto newIndexMetaMethod = [&](OverridableX& x, const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State* L) -> luabridge::LuaRef { x.data.emplace(std::make_pair(key, value)); return luabridge::LuaRef(L); }; luabridge::getGlobalNamespace(L) .beginClass("X", luabridge::extensibleClass) .addIndexMetaMethod(indexMetaMethod) .addNewIndexMetaMethod(newIndexMetaMethod) .endClass(); OverridableX x, y; luabridge::setGlobal(L, &x, "x"); luabridge::setGlobal(L, &y, "y"); runLua(R"( X.xyz = 1 function X:setProperty(v) self.xyz = v end function X:getProperty() return self.xyz end y.xyz = 100 x:setProperty(2) result = x.xyz + y.xyz )"); ASSERT_EQ(102, result()); } TEST_F(ClassExtensibleTests, IndexFallbackMetaMethodFreeFunctorOnClassOverwriteProperty) { auto indexMetaMethod = [&](OverridableX& x, const luabridge::LuaRef& key, lua_State* L) -> luabridge::LuaRef { auto it = x.data.find(key); if (it != x.data.end()) return it->second; return luabridge::LuaRef(L); }; auto newIndexMetaMethod = [&](OverridableX& x, const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State* L) -> luabridge::LuaRef { x.data.emplace(std::make_pair(key, value)); return luabridge::LuaRef(L); }; luabridge::getGlobalNamespace(L) .beginClass("X", luabridge::extensibleClass | luabridge::allowOverridingMethods) .addIndexMetaMethod(indexMetaMethod) .addNewIndexMetaMethod(newIndexMetaMethod) .endClass(); OverridableX x, y; luabridge::setGlobal(L, &x, "x"); luabridge::setGlobal(L, &y, "y"); runLua(R"( function X:property(v) self.property = v end x:property(2) result = x.property )"); ASSERT_TRUE(result().isNumber()); EXPECT_EQ(2, result()); } TEST_F(ClassExtensibleTests, NewIndexFallbackMetaMethodMemberFptr) { luabridge::getGlobalNamespace(L) .beginClass("X") .addIndexMetaMethod(&OverridableX::indexMetaMethod) .addNewIndexMetaMethod(&OverridableX::newIndexMetaMethod) .endClass(); OverridableX x; luabridge::setGlobal(L, &x, "x"); runLua("x.qwertyuiop = 123; result = x.qwertyuiop"); ASSERT_EQ(123, result()); } TEST_F(ClassExtensibleTests, NewIndexFallbackMetaMethodFunctionPtr) { luabridge::getGlobalNamespace(L) .beginClass("X") .addIndexMetaMethod(&indexMetaMethodFunction) .addNewIndexMetaMethod(&newIndexMetaMethodFunction) .endClass(); OverridableX x; luabridge::setGlobal(L, &x, "x"); runLua("x.qwertyuiop = 123; result = x.qwertyuiop"); ASSERT_EQ(123, result()); } TEST_F(ClassExtensibleTests, NewIndexFallbackMetaMethodFreeFunctor) { int capture = 123; auto newIndexMetaMethod = [&capture](OverridableX& x, const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State* L) -> luabridge::LuaRef { if (!luabridge::push(L, capture + value.unsafe_cast())) lua_pushnil(L); auto v = luabridge::LuaRef::fromStack(L); x.data.emplace(std::make_pair(key, v)); return v; }; luabridge::getGlobalNamespace(L) .beginClass("X") .addIndexMetaMethod(&indexMetaMethodFunction) .addNewIndexMetaMethod(newIndexMetaMethod) .endClass(); OverridableX x; luabridge::setGlobal(L, &x, "x"); runLua("x.qwertyuiop = 123; result = x.qwertyuiop"); ASSERT_EQ(246, result()); } namespace { struct ExtensibleBase { ExtensibleBase() = default; int baseClass() { return 1; } int baseClassConst() const { return 2; } std::unordered_map properties; }; struct ExtensibleDerived : ExtensibleBase { ExtensibleDerived() = default; int derivedClass() { return 11; } int derivedClassConst() const { return 22; } }; struct SimplePropertyClass { int value = 17; int getValue() const { return value; } }; } // namespace TEST_F(ClassExtensibleTests, ExtensibleClass) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .endClass() ; runLua(R"( function ExtensibleBase:test() return 41 + self:baseClass() end local base = ExtensibleBase(); result = base:test() )"); EXPECT_EQ(42, result()); } TEST_F(ClassExtensibleTests, ExtensibleBaseClassNotDerived) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .endClass() .deriveClass("ExtensibleDerived") .addConstructor() .endClass() ; runLua(R"( function ExtensibleBase:test() return 41 + self:baseClass() end local derived = ExtensibleDerived(); result = derived:test() )"); EXPECT_EQ(42, result()); } TEST_F(ClassExtensibleTests, ExtensibleDerivedClassNotBase) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase") .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .endClass() .deriveClass("ExtensibleDerived", luabridge::extensibleClass) .addConstructor() .endClass() ; runLua(R"( function ExtensibleDerived:test() return 41 + self:baseClass() end local derived = ExtensibleDerived(); result = derived:test() )"); EXPECT_EQ(42, result()); } TEST_F(ClassExtensibleTests, ExtensibleDerivedClassAndBase) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .endClass() .deriveClass("ExtensibleDerived", luabridge::extensibleClass) .addConstructor() .addFunction("derivedClass", &ExtensibleDerived::derivedClass) .endClass() ; runLua(R"( function ExtensibleBase:test1() return self:baseClass() end function ExtensibleDerived:test2() return self:derivedClass() end local derived = ExtensibleDerived(); result = derived:test1() - derived:test2() )"); EXPECT_EQ(-10, result()); } TEST_F(ClassExtensibleTests, ExtensibleDerivedClassAndBaseCascading) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .endClass() .deriveClass("ExtensibleDerived", luabridge::extensibleClass) .addConstructor() .addFunction("derivedClass", &ExtensibleDerived::derivedClass) .endClass() ; runLua(R"( function ExtensibleBase:testBase() return self:baseClass() end function ExtensibleDerived:testDerived() return self:testBase() end local derived = ExtensibleDerived(); result = derived:testDerived() )"); EXPECT_EQ(1, result()); } TEST_F(ClassExtensibleTests, ExtensibleParentLuaMethodVisibleFromDerived) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .endClass() .deriveClass("ExtensibleDerived") .addConstructor() .endClass() ; runLua(R"( function ExtensibleBase:luaOnlyMethod() return 123 end local derived = ExtensibleDerived() result = derived:luaOnlyMethod() )"); EXPECT_EQ(123, result()); } TEST_F(ClassExtensibleTests, SimpleUserdataPropertyLookupFastPath) { luabridge::getGlobalNamespace(L) .beginClass("SimplePropertyClass") .addConstructor() .addProperty("value", &SimplePropertyClass::getValue) .endClass() ; runLua(R"( local obj = SimplePropertyClass() local valueOk = obj.value == 17 local missingIsNil = obj.missing == nil result = valueOk and missingIsNil )"); EXPECT_TRUE(result()); } TEST_F(ClassExtensibleTests, ExtensibleDerivedClassAndBaseSameMethod) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .endClass() .deriveClass("ExtensibleDerived", luabridge::extensibleClass) .addConstructor() .endClass() ; runLua(R"( function ExtensibleBase:test() return 1337 end function ExtensibleBase:test() return 1338 end -- This is on purpose function ExtensibleDerived:test() return 42 end local derived = ExtensibleDerived() result = derived:test() )"); EXPECT_EQ(42, result()); } TEST_F(ClassExtensibleTests, ExtensibleClassExtendExistingMethod) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .addFunction("baseClassConst", &ExtensibleBase::baseClassConst) .endClass() ; #if LUABRIDGE_HAS_EXCEPTIONS EXPECT_ANY_THROW(runLua(R"( function ExtensibleBase:baseClass() return 42 end local base = ExtensibleBase(); result = base:baseClass() )")); #else EXPECT_FALSE(runLua(R"( function ExtensibleBase:baseClass() return 42 end local base = ExtensibleBase(); result = base:baseClass() )")); #endif #if LUABRIDGE_HAS_EXCEPTIONS EXPECT_ANY_THROW(runLua(R"( function ExtensibleBase:baseClassConst() return 42 end local base = ExtensibleBase(); result = base:baseClassConst() )")); #else EXPECT_FALSE(runLua(R"( function ExtensibleBase:baseClassConst() return 42 end local base = ExtensibleBase(); result = base:baseClassConst() )")); #endif } TEST_F(ClassExtensibleTests, ExtensibleClassExtendExistingMethodAllowingOverride) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass | luabridge::allowOverridingMethods) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .addFunction("baseClassConst", &ExtensibleBase::baseClassConst) .endClass() ; runLua(R"( function ExtensibleBase:baseClass() return 42 + self:super_baseClass() end local base = ExtensibleBase() result = base:baseClass() )"); EXPECT_EQ(43, result()); runLua(R"( function ExtensibleBase:baseClassConst() return 42 + self:super_baseClassConst() end local base = ExtensibleBase() result = base:baseClassConst() )"); EXPECT_EQ(44, result()); } TEST_F(ClassExtensibleTests, ExtensibleDerivedOverrideOneFunctionCallBaseForTheOther) { constexpr auto options = luabridge::extensibleClass | luabridge::allowOverridingMethods; luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", options) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .addFunction("baseClassConst", &ExtensibleBase::baseClassConst) .endClass() .deriveClass("ExtensibleDerived", options) .addConstructor() .addFunction("derivedClass", &ExtensibleDerived::derivedClass) .addFunction("derivedClassConst", &ExtensibleDerived::derivedClassConst) .endClass() ; runLua(R"( function ExtensibleDerived:baseClass() return 100 + self:super_baseClass() end local derived = ExtensibleDerived() result = derived:baseClass() + derived:baseClassConst() )"); EXPECT_EQ(103, result()); } TEST_F(ClassExtensibleTests, ExtensibleDerivedDoesNotPollutBaseMethod) { // Regression test: defining a Lua method on a derived class must NOT overwrite the // same-named method on the base class (the originally reported inheritance bug). luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .endClass() .deriveClass("ExtensibleDerived", luabridge::extensibleClass) .addConstructor() .endClass() ; runLua(R"( function ExtensibleBase:init() return 100 end function ExtensibleDerived:init() return 200 end local base = ExtensibleBase() local derived = ExtensibleDerived() result = base:init() )"); // base:init() must return 100 (the Base version), not 200 (the Derived version) EXPECT_EQ(100, result()); } TEST_F(ClassExtensibleTests, ExtensibleDerivedMethodIsolatedFromBase) { // Verify both sides independently after same-name Lua methods are defined on each class. luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .endClass() .deriveClass("ExtensibleDerived", luabridge::extensibleClass) .addConstructor() .endClass() ; runLua(R"( function ExtensibleBase:getValue() return 10 end function ExtensibleDerived:getValue() return 20 end local base = ExtensibleBase() local derived = ExtensibleDerived() result = derived:getValue() * 100 + base:getValue() )"); // derived:getValue() == 20, base:getValue() == 10 => 20*100 + 10 == 2010 EXPECT_EQ(2010, result()); } TEST_F(ClassExtensibleTests, ExtensibleDerivedOverridePreservesCppBaseMethod) { // When allowOverridingMethods is set and a derived class overrides a C++ method, // the base class should still call the original C++ implementation. constexpr auto options = luabridge::extensibleClass | luabridge::allowOverridingMethods; luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", options) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .endClass() .deriveClass("ExtensibleDerived", options) .addConstructor() .endClass() ; runLua(R"( -- Override baseClass only on ExtensibleDerived; base must remain unaffected function ExtensibleDerived:baseClass() return 100 + self:super_baseClass() end local base = ExtensibleBase() local derived = ExtensibleDerived() result = derived:baseClass() * 1000 + base:baseClass() )"); // derived:baseClass() == 100 + 1 == 101, base:baseClass() == 1 (original C++) // => 101 * 1000 + 1 == 101001 EXPECT_EQ(101001, result()); } TEST_F(ClassExtensibleTests, ExtensibleObjectNonFunctionWriteCanReplaceMethodWithSuper) { constexpr auto options = luabridge::extensibleClass | luabridge::allowOverridingMethods; luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", options) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .endClass() ; ASSERT_TRUE(runLua(R"( local base = ExtensibleBase() base.baseClass = 41 result = true )")); EXPECT_TRUE(result()); } TEST_F(ClassExtensibleTests, ExtensibleObjectNonFunctionWriteTraversesParentAndUpdatesExistingValue) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .endClass() .deriveClass("ExtensibleDerived", luabridge::extensibleClass) .addConstructor() .endClass() ; runLua(R"( local derived = ExtensibleDerived() derived.dynamicValue = 10 derived.dynamicValue = 20 result = derived.dynamicValue )"); EXPECT_EQ(20, result()); } TEST_F(ClassExtensibleTests, ExtensibleClassCustomMetamethods) { auto options = luabridge::allowOverridingMethods | luabridge::extensibleClass; luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", options) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .endClass() ; runLua(R"( function ExtensibleBase:__tostring() return ('ExtensibleBase(%d)'):format(self:baseClass()) end local base = ExtensibleBase(); result = tostring(base) )"); EXPECT_EQ("ExtensibleBase(1)", result()); } TEST_F(ClassExtensibleTests, ExtensibleClassCustomMetamethodsSuper) { auto options = luabridge::allowOverridingMethods | luabridge::extensibleClass; luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", options) .addConstructor() .endClass() ; runLua(R"( function ExtensibleBase:__tostring() return '123456 - ' .. self:super__tostring() end local base = ExtensibleBase(); result = tostring(base) )"); EXPECT_EQ(0u, result().find("123456")); EXPECT_NE(std::string::npos, result().find("ExtensibleBase")); } TEST_F(ClassExtensibleTests, ExtensibleClassCustomMetamethodEq) { auto options = luabridge::allowOverridingMethods | luabridge::extensibleClass; luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", options) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .endClass() ; runLua(R"( function ExtensibleBase:__eq(other) return self:baseClass() == other:baseClass() end local base1 = ExtensibleBase() local base2 = ExtensibleBase() result = base1 == base2 )"); EXPECT_TRUE(result()); } TEST_F(ClassExtensibleTests, ExtensibleClassWithCustomIndexMethod) { luabridge::getGlobalNamespace(L) .beginClass("ExtensibleBase", luabridge::extensibleClass) .addConstructor() .addFunction("baseClass", &ExtensibleBase::baseClass) .addIndexMetaMethod([](ExtensibleBase& self, const luabridge::LuaRef& key, lua_State* L) { auto it = self.properties.find(key); if (it != self.properties.end()) return it->second; return luabridge::LuaRef(L); }) .addNewIndexMetaMethod([](ExtensibleBase& self, const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State* L) { self.properties.emplace(std::make_pair (key, value)); return luabridge::LuaRef(L); }) .endClass() ; runLua(R"( function ExtensibleBase:test() return 41 + self.xyz + self:baseClass() end local base = ExtensibleBase() base.xyz = 1000 result = base:test() )"); EXPECT_EQ(1042, result()); runLua(R"( ExtensibleBase.staticProperty = 101; result = ExtensibleBase.staticProperty )"); EXPECT_EQ(101, result()); runLua(R"( ExtensibleBase.staticProperty = nil; result = ExtensibleBase.staticProperty )"); EXPECT_TRUE(result().isNil()); } namespace { class NonExtensible { public: luabridge::LuaRef getProperty(const luabridge::LuaRef& key, lua_State* L) { auto it = properties.find(key); if (it != properties.end()) return it->second; return luabridge::LuaRef(L); } luabridge::LuaRef setProperty(const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State* L) { properties.emplace(key, value); return luabridge::LuaRef(L); } private: std::unordered_map properties; }; class DerivedExtensible : public NonExtensible { public: inline DerivedExtensible() {}; }; } // namespace TEST_F(ClassExtensibleTests, IndexAndNewMetaMethodCalledInBaseClass) { luabridge::getGlobalNamespace(L) .beginClass("NonExtensible") .addIndexMetaMethod(&NonExtensible::getProperty) .addNewIndexMetaMethod(&NonExtensible::setProperty) .endClass() .deriveClass("DerivedExtensible", luabridge::extensibleClass) .addConstructor() .endClass(); runLua(R"( DerivedExtensible.property = 100 function DerivedExtensible:getProperty() return self.property end function DerivedExtensible:setProperty(value) self.property = value end local test = DerivedExtensible() test:setProperty(2) result = test:getProperty() + DerivedExtensible.property )"); EXPECT_EQ(102, result()); runLua(R"( local test = DerivedExtensible() test.property = 3 result = test.property )"); EXPECT_EQ(3, result()); } namespace { class ExampleStringifiableClass { public: ExampleStringifiableClass() : a(0), b(0), c(0) { } std::string tostring() const { return "whatever"; } int a, b, c; }; } // namespace TEST_F(ClassExtensibleTests, MetatableSecurityNotHidden) { { luabridge::getGlobalNamespace(L) .beginNamespace("test", luabridge::visibleMetatables) .endNamespace(); runLua("local t = test; result = getmetatable(t)"); const auto res = result(); ASSERT_TRUE(res.isTable()); } { luabridge::getGlobalNamespace(L) .beginClass("ExampleStringifiableClass", luabridge::visibleMetatables) .addConstructor() .addFunction("__tostring", &ExampleStringifiableClass::tostring) .endClass(); runLua("local t = ExampleStringifiableClass(); result = getmetatable(t)"); const auto res = result(); ASSERT_TRUE(res.isTable()); } } TEST_F(ClassExtensibleTests, MetatableSecurity) { { luabridge::getGlobalNamespace(L) .beginNamespace("test") .endNamespace(); runLua("local t = test; result = getmetatable(t)"); const auto res = result(); ASSERT_TRUE(res.isBool()); EXPECT_FALSE(res.unsafe_cast()); } { luabridge::getGlobalNamespace(L) .beginClass("ExampleStringifiableClass") .addConstructor() .addFunction("__tostring", &ExampleStringifiableClass::tostring) .endClass(); runLua("local t = ExampleStringifiableClass(); result = getmetatable(t)"); const auto res = result(); ASSERT_TRUE(res.isBool()); EXPECT_FALSE(res.unsafe_cast()); } } #if ! LUABRIDGE_ON_LUAU && LUA_VERSION_NUM >= 502 TEST_F(ClassExtensibleTests, MetatablePrinting) { luabridge::getGlobalNamespace(L) .beginClass("ExampleStringifiableClass", luabridge::visibleMetatables) .addConstructor() .endClass(); runLua(R"( local text = '' local mt = getmetatable(ExampleStringifiableClass) for k, v in pairs(mt) do text = text .. ('%s - %s'):format(k, v) end result = text )"); const auto res = result(); ASSERT_TRUE(res.isString()); EXPECT_FALSE(res.unsafe_cast().empty()); } #endif namespace { struct StaticMetamethodClass { StaticMetamethodClass() = default; }; luabridge::LuaRef staticIndexFallbackFunction(const luabridge::LuaRef& key, lua_State* L) { if (key.tostring() == "xyz") { if (!luabridge::push(L, 42)) lua_pushnil(L); return luabridge::LuaRef::fromStack(L); } return luabridge::LuaRef(L); } luabridge::LuaRef staticNewIndexFallbackFunction(const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State* L) { return value; } } // namespace TEST_F(ClassExtensibleTests, StaticIndexFallbackMetaMethodFunctionPtr) { luabridge::getGlobalNamespace(L) .beginClass("X") .addStaticIndexMetaMethod(&staticIndexFallbackFunction) .endClass(); runLua("result = X.xyz"); ASSERT_EQ(42, result()); } TEST_F(ClassExtensibleTests, StaticIndexFallbackMetaMethodFreeFunctor) { std::string capture = "hello"; auto indexMetaMethod = [&capture](const luabridge::LuaRef& key, lua_State* L) -> luabridge::LuaRef { if (key.tostring() == "greeting") { if (!luabridge::push(L, capture)) lua_pushnil(L); return luabridge::LuaRef::fromStack(L); } return luabridge::LuaRef(L); }; luabridge::getGlobalNamespace(L) .beginClass("X") .addStaticIndexMetaMethod(indexMetaMethod) .endClass(); runLua("result = X.greeting"); ASSERT_EQ("hello", result()); } TEST_F(ClassExtensibleTests, StaticNewIndexFallbackMetaMethodFunctionPtr) { // Verify that assigning to an unknown static key invokes the newindex fallback // (staticNewIndexFallbackFunction is a plain function pointer that accepts the assignment). // Without the fallback, assigning to an unknown key would raise a Lua error. // We also confirm reading the key still goes through the index fallback. luabridge::getGlobalNamespace(L) .beginClass("X") .addStaticIndexMetaMethod(&staticIndexFallbackFunction) .addStaticNewIndexMetaMethod(&staticNewIndexFallbackFunction) .endClass(); // staticIndexFallbackFunction always returns 42 for "xyz" ASSERT_TRUE(runLua("X.xyz = 100")); // must not error: newindex fallback handles it runLua("result = X.xyz"); ASSERT_EQ(42, result()); // index fallback still returns 42 regardless of assignment } TEST_F(ClassExtensibleTests, StaticNewIndexFallbackMetaMethodFreeFunctor) { std::unordered_map data; auto indexMetaMethod = [&data](const luabridge::LuaRef& key, lua_State* L) -> luabridge::LuaRef { auto it = data.find(key.tostring()); if (it != data.end()) { if (!luabridge::push(L, it->second)) lua_pushnil(L); return luabridge::LuaRef::fromStack(L); } return luabridge::LuaRef(L); }; auto newIndexMetaMethod = [&data](const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State*) -> luabridge::LuaRef { if (value.isNumber()) data.emplace(key.tostring(), value.unsafe_cast()); return value; }; luabridge::getGlobalNamespace(L) .beginClass("X") .addStaticIndexMetaMethod(indexMetaMethod) .addStaticNewIndexMetaMethod(newIndexMetaMethod) .endClass(); runLua("X.foo = 111; X.bar = 222; result = X.foo + X.bar"); ASSERT_EQ(333, result()); } TEST_F(ClassExtensibleTests, StaticIndexFallbackReturnsNilForUnknownKey) { auto indexMetaMethod = [](const luabridge::LuaRef& key, lua_State* L) -> luabridge::LuaRef { if (key.tostring() == "known") { if (!luabridge::push(L, 77)) lua_pushnil(L); return luabridge::LuaRef::fromStack(L); } return luabridge::LuaRef(L); }; luabridge::getGlobalNamespace(L) .beginClass("X") .addStaticIndexMetaMethod(indexMetaMethod) .endClass(); runLua("result = X.known"); ASSERT_EQ(77, result()); runLua("result = X.unknown"); ASSERT_TRUE(result().isNil()); } TEST_F(ClassExtensibleTests, StaticIndexFallbackFallsThroughToExistingStaticProperty) { // When the fallback returns nil for a key, the real static property must still be found. int staticValue = 99; auto indexMetaMethod = [](const luabridge::LuaRef& /*key*/, lua_State* L) -> luabridge::LuaRef { // Always return nil so normal lookup proceeds return luabridge::LuaRef(L); }; luabridge::getGlobalNamespace(L) .beginClass("X") .addStaticProperty("answer", [&staticValue] { return staticValue; }) .addStaticIndexMetaMethod(indexMetaMethod) .endClass(); runLua("result = X.answer"); ASSERT_EQ(99, result()); } TEST_F(ClassExtensibleTests, StaticIndexFallbackFallsThroughToExistingStaticFunction) { // When the fallback returns nil for a key, an existing static function must still be callable. auto indexMetaMethod = [](const luabridge::LuaRef& /*key*/, lua_State* L) -> luabridge::LuaRef { return luabridge::LuaRef(L); }; luabridge::getGlobalNamespace(L) .beginClass("X") .addStaticFunction("compute", []() { return 7; }) .addStaticIndexMetaMethod(indexMetaMethod) .endClass(); runLua("result = X.compute()"); ASSERT_EQ(7, result()); } TEST_F(ClassExtensibleTests, StaticIndexFallbackCanShadowExistingStaticProperty) { // When the fallback returns a non-nil value for a key that also exists as a static // property, the fallback result takes priority. int staticValue = 10; auto indexMetaMethod = [](const luabridge::LuaRef& key, lua_State* L) -> luabridge::LuaRef { if (key.tostring() == "answer") { if (!luabridge::push(L, 999)) lua_pushnil(L); return luabridge::LuaRef::fromStack(L); } return luabridge::LuaRef(L); }; luabridge::getGlobalNamespace(L) .beginClass("X") .addStaticProperty("answer", [&staticValue] { return staticValue; }) .addStaticIndexMetaMethod(indexMetaMethod) .endClass(); // Fallback returns 999 for "answer", not the registered property value (10) runLua("result = X.answer"); ASSERT_EQ(999, result()); } TEST_F(ClassExtensibleTests, StaticNewIndexFallbackStandaloneWithoutIndexFallback) { // newindex fallback should work even when no index fallback is registered. // Assigning to an unknown key must not raise an error. bool callbackInvoked = false; auto newIndexMetaMethod = [&callbackInvoked](const luabridge::LuaRef& /*key*/, const luabridge::LuaRef& value, lua_State*) -> luabridge::LuaRef { callbackInvoked = true; return value; }; luabridge::getGlobalNamespace(L) .beginClass("X") .addStaticNewIndexMetaMethod(newIndexMetaMethod) .endClass(); ASSERT_TRUE(runLua("X.whatever = 42")); ASSERT_TRUE(callbackInvoked); } TEST_F(ClassExtensibleTests, StaticIndexAndNewIndexFallbackCoexistWithStaticProperty) { // Register both fallbacks alongside a real static property. // The fallback store handles unknown keys; the real property is unaffected. std::unordered_map store; int staticValue = 55; auto indexMetaMethod = [&store](const luabridge::LuaRef& key, lua_State* L) -> luabridge::LuaRef { auto it = store.find(key.tostring()); if (it != store.end()) { if (!luabridge::push(L, it->second)) lua_pushnil(L); return luabridge::LuaRef::fromStack(L); } return luabridge::LuaRef(L); }; auto newIndexMetaMethod = [&store](const luabridge::LuaRef& key, const luabridge::LuaRef& value, lua_State*) -> luabridge::LuaRef { if (value.isNumber()) store[key.tostring()] = value.unsafe_cast(); return value; }; luabridge::getGlobalNamespace(L) .beginClass("X") .addStaticProperty("base", [&staticValue] { return staticValue; }) .addStaticIndexMetaMethod(indexMetaMethod) .addStaticNewIndexMetaMethod(newIndexMetaMethod) .endClass(); // Real static property is accessible runLua("result = X.base"); ASSERT_EQ(55, result()); // Unknown key goes through the fallback store runLua("X.extra = 100; result = X.extra"); ASSERT_EQ(100, result()); // Real property is still accessible after fallback store mutations runLua("result = X.base"); ASSERT_EQ(55, result()); }