From 7388afe7b3253220e54aa9c37bbea44477824669 Mon Sep 17 00:00:00 2001 From: Stephan Hadinger Date: Fri, 29 Dec 2023 09:45:06 +0100 Subject: [PATCH] Berry added `introspect.set()` for class attributes --- CHANGELOG.md | 1 + lib/libesp32/berry/src/be_api.c | 4 ++++ lib/libesp32/berry/src/be_introspectlib.c | 2 +- lib/libesp32/berry/tests/introspect.be | 22 ++++++++++++++++++++++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 759b427a325d..d24aea8b2872 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ All notable changes to this project will be documented in this file. - Display of active drivers using command ``status 4`` - ESP32 used UART information - HASPmota added `haspmota.page_show()` to change page +- Berry added `introspect.set()` for class attributes ### Breaking Changed - Refactoring of Berry `animate` module for WS2812 Leds (#20236) diff --git a/lib/libesp32/berry/src/be_api.c b/lib/libesp32/berry/src/be_api.c index ba5b915d2d9d..5cc7559297fa 100644 --- a/lib/libesp32/berry/src/be_api.c +++ b/lib/libesp32/berry/src/be_api.c @@ -643,6 +643,10 @@ BERRY_API bbool be_setmember(bvm *vm, int index, const char *k) bstring *key = be_newstr(vm, k); bmodule *mod = var_toobj(o); return be_module_setmember(vm, mod, key, v); + } else if (var_isclass(o)) { + bstring *key = be_newstr(vm, k); + bclass *cl = var_toobj(o); + return be_class_setmember(vm, cl, key, v); } return bfalse; } diff --git a/lib/libesp32/berry/src/be_introspectlib.c b/lib/libesp32/berry/src/be_introspectlib.c index 4f98f2d94e07..73e2da466f35 100644 --- a/lib/libesp32/berry/src/be_introspectlib.c +++ b/lib/libesp32/berry/src/be_introspectlib.c @@ -96,7 +96,7 @@ static int m_findmember(bvm *vm) static int m_setmember(bvm *vm) { int top = be_top(vm); - if (top >= 3 && (be_isinstance(vm, 1) || be_ismodule(vm, 1)) && be_isstring(vm, 2)) { + if (top >= 3 && (be_isinstance(vm, 1) || be_ismodule(vm, 1) || be_isclass(vm, 1)) && be_isstring(vm, 2)) { be_setmember(vm, 1, be_tostring(vm, 2)); be_return(vm); } diff --git a/lib/libesp32/berry/tests/introspect.be b/lib/libesp32/berry/tests/introspect.be index c93033982e72..1d9c7af293cc 100644 --- a/lib/libesp32/berry/tests/introspect.be +++ b/lib/libesp32/berry/tests/introspect.be @@ -42,3 +42,25 @@ assert(introspect.name(A) == 'A') assert(introspect.name(A.a) == 'a') assert(introspect.name(A.b) == 'b') assert(introspect.name(A.c) == nil) + +# test introspect get and set +# class and instance +class A + static var a + var b +end + +a = A() +introspect.set(A, "a", 10) +assert(A.a == 10) +assert(introspect.get(A, "a") == 10) + +introspect.set(a, "b", 20) +assert(a.b == 20) +assert(introspect.get(a, "b") == 20) + +# module +m = module('m') +introspect.set(m, 'c', 30) +assert(m.c == 30) +assert(introspect.get(m, 'c') == 30)