From 77da776b9e1199ffc266c878c951f76c2506512c Mon Sep 17 00:00:00 2001 From: aster2013 Date: Thu, 7 Jul 2016 18:39:02 +0800 Subject: [PATCH 1/2] Add external property getter and setter function. --- include/kaguya/metatable.hpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/include/kaguya/metatable.hpp b/include/kaguya/metatable.hpp index 85d154f..160188a 100644 --- a/include/kaguya/metatable.hpp +++ b/include/kaguya/metatable.hpp @@ -186,6 +186,24 @@ namespace kaguya return *this; } + /** + * @name addProperty + * @brief add member property with external getter function.(experimental) + * @param name function name for lua + * @param getter getter function + */ + template + UserdataMetatable& addProperty(const char* name, GetType(*getter)(const class_type*)) + { + if (has_key(name)) + { + throw KaguyaException("already registered."); + return *this; + } + property_map_[name] = AnyDataPusher(function(getter)); + return *this; + } + /** * @name addProperty * @brief add member property with setter, getter functions.(experimental) @@ -205,6 +223,24 @@ namespace kaguya return *this; } + /** + * @name addProperty + * @brief add member property with external setter, getter functions.(experimental) + * @param name function name for lua + * @param getter getter function + * @param setter setter function + */ + template + UserdataMetatable& addProperty(const char* name, GetType(*getter)(const class_type*), void (*setter)(class_type*, SetType)) + { + if (has_key(name)) + { + throw KaguyaException("already registered."); + return *this; + } + property_map_[name] = AnyDataPusher(overload(getter, setter)); + return *this; + } /** * @name addStaticFunction From 0e4362ae285fae1e896d59ad1df273e1b4b08e4b Mon Sep 17 00:00:00 2001 From: satoren Date: Mon, 8 Aug 2016 20:58:22 +0900 Subject: [PATCH 2/2] add test for addProperty by external function --- test/test_02_classreg.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/test/test_02_classreg.cpp b/test/test_02_classreg.cpp index fc1465d..d284c86 100644 --- a/test/test_02_classreg.cpp +++ b/test/test_02_classreg.cpp @@ -1401,4 +1401,26 @@ KAGUYA_TEST_FUNCTION_DEF(self_refcounted_object)(kaguya::State& ) } +int Base_a_getter(const Base* self) +{ + return self->a; +} +void Base_a_setter(Base* self,int v) +{ + self->a = v; +} +KAGUYA_TEST_FUNCTION_DEF(add_property_external)(kaguya::State& state) +{ + + state["Base"].setClass(kaguya::UserdataMetatable() + .setConstructors() + .addProperty("a", &Base_a_getter,&Base_a_setter) + ); + Base base; + state["base"] = &base; + TEST_CHECK(state("base.a=1")); + TEST_CHECK(state("assert(1 == base.a)")); + TEST_EQUAL(base.a, 1); +} + KAGUYA_TEST_GROUP_END(test_02_classreg)