Add krk_valueGetAttribute_default
This commit is contained in:
parent
05f7d9537a
commit
aaac0c168a
@ -678,13 +678,11 @@ KRK_FUNC(getattr,{
|
||||
FUNCTION_TAKES_AT_LEAST(2);
|
||||
KrkValue object = argv[0];
|
||||
CHECK_ARG(1,str,KrkString*,property);
|
||||
KrkValue result = krk_valueGetAttribute(object, property->chars);
|
||||
if (argc == 3 && krk_currentThread.flags & KRK_THREAD_HAS_EXCEPTION &&
|
||||
krk_isInstanceOf(krk_currentThread.currentException, vm.exceptions->attributeError)) {
|
||||
krk_currentThread.flags &= ~(KRK_THREAD_HAS_EXCEPTION);
|
||||
result = argv[2];
|
||||
if (argc == 3) {
|
||||
return krk_valueGetAttribute_default(object, property->chars, argv[2]);
|
||||
} else {
|
||||
return krk_valueGetAttribute(object, property->chars);
|
||||
}
|
||||
return result;
|
||||
})
|
||||
|
||||
KRK_FUNC(setattr,{
|
||||
|
13
src/vm.c
13
src/vm.c
@ -1764,6 +1764,19 @@ KrkValue krk_valueGetAttribute(KrkValue value, char * name) {
|
||||
return krk_pop();
|
||||
}
|
||||
|
||||
KrkValue krk_valueGetAttribute_default(KrkValue value, char * name, KrkValue defaultVal) {
|
||||
krk_push(OBJECT_VAL(krk_copyString(name,strlen(name))));
|
||||
krk_push(value);
|
||||
if (!valueGetProperty(AS_STRING(krk_peek(1)))) {
|
||||
krk_pop();
|
||||
krk_pop();
|
||||
return defaultVal;
|
||||
}
|
||||
krk_swap(1);
|
||||
krk_pop(); /* String */
|
||||
return krk_pop();
|
||||
}
|
||||
|
||||
static int valueDelProperty(KrkString * name) {
|
||||
if (IS_INSTANCE(krk_peek(0))) {
|
||||
KrkInstance* instance = AS_INSTANCE(krk_peek(0));
|
||||
|
5
src/vm.h
5
src/vm.h
@ -743,6 +743,11 @@ extern int krk_isFalsey(KrkValue value);
|
||||
*/
|
||||
extern KrkValue krk_valueGetAttribute(KrkValue value, char * name);
|
||||
|
||||
/**
|
||||
* @brief See @ref krk_valueGetAttribute
|
||||
*/
|
||||
extern KrkValue krk_valueGetAttribute_default(KrkValue value, char * name, KrkValue defaultVal);
|
||||
|
||||
/**
|
||||
* @brief Set a property of an object by name.
|
||||
* @memberof KrkValue
|
||||
|
Loading…
Reference in New Issue
Block a user