From 6d45c0a6768d9e5a3bc809d7b2a7bd6c83da694f Mon Sep 17 00:00:00 2001 From: CPunch Date: Fri, 20 Nov 2020 15:10:49 -0600 Subject: [PATCH] fixed __index --- examples/increment.cosmo | 28 ++++++++++++++++++++++++++++ src/cobj.c | 8 +++++--- 2 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 examples/increment.cosmo diff --git a/examples/increment.cosmo b/examples/increment.cosmo new file mode 100644 index 0000000..81f9dbd --- /dev/null +++ b/examples/increment.cosmo @@ -0,0 +1,28 @@ +class Stack + function __init(self) + self.stack = {} + self.x = 0 + end + + function push(self, val) + self.stack[self.x++] = val + end + + function pop(self) + return self.stack[--self.x] + end + + function __index(self, key) + return self.stack[key] + end +end + +var stack = Stack() + +for (var i = 0; i < 10000; i++) do + stack.push(i) +end + +for (var i = 0; i < 10000; i++) do + print(stack.pop() .. " : " .. stack[i]) +end \ No newline at end of file diff --git a/src/cobj.c b/src/cobj.c index e9bbf0d..bc90dc6 100644 --- a/src/cobj.c +++ b/src/cobj.c @@ -206,7 +206,11 @@ CObjString *cosmoO_allocateString(CState *state, const char *str, size_t sz, uin bool cosmoO_getObject(CState *state, CObjObject *object, CValue key, CValue *val) { if (!cosmoT_get(&object->tbl, key, val)) { // if the field doesn't exist in the object, check the proto if (object->proto != NULL) { // sanity check - // first though, check for __index, if that exists, call it + // first though, check for a member of the proto object, if it fails then lookup __index + if (cosmoO_getObject(state, object->proto, key, val)) + return true; + + // then check for __index, if that exists, call it if (cosmoO_getIString(state, object->proto, ISTRING_INDEX, val)) { cosmoV_pushValue(state, *val); // push function cosmoV_pushValue(state, cosmoV_newObj(object)); // push object @@ -215,8 +219,6 @@ bool cosmoO_getObject(CState *state, CObjObject *object, CValue key, CValue *val *val = *cosmoV_pop(state); // set value to the return value of __index return true; } - - return cosmoO_getObject(state, object->proto, key, val); } return false; // no protoobject to check against