summaryrefslogtreecommitdiff
path: root/val.c
diff options
context:
space:
mode:
authorubq323 <ubq323@ubq323.website>2024-06-26 19:27:42 +0100
committerubq323 <ubq323@ubq323.website>2024-06-26 19:27:42 +0100
commit2e62b41072738142dea9f0b5dd5d2d22455c7616 (patch)
treef47ce547de39fb69b02eb70990c9485489f1e574 /val.c
parent6deeb9630d4b4e7d672ab851dcd4fe3d0d3d2865 (diff)
add arrays, appending, getting length, indexing
Diffstat (limited to 'val.c')
-rw-r--r--val.c54
1 files changed, 51 insertions, 3 deletions
diff --git a/val.c b/val.c
index 7c8b25a..6562daa 100644
--- a/val.c
+++ b/val.c
@@ -3,6 +3,7 @@
#include "val.h"
#include "mem.h"
#include "ht.h"
+#include "util.h"
static ObjString *objstring_create(State*, char*, size_t, uint32_t);
@@ -55,7 +56,40 @@ ObjFunc *objfunc_new(State *S, uint8_t arity) {
}
-void print_val(Val v) {
+ObjArr *objarr_new(State *S) {
+ ObjArr *o = NEW_OBJ(S, ObjArr, OTY_ARR);
+ o->len = 0;
+ o->cap = 0;
+ o->d = NULL;
+ return o;
+}
+
+Val objarr_get(State *S, ObjArr *arr, size_t ix) {
+ CHECK(ix < arr->len, "array index out of bounds");
+ return arr->d[ix];
+}
+void objarr_append(State *S, ObjArr *arr, Val v) {
+ if (arr->len == arr->cap) {
+ size_t newsz = (arr->cap == 0 ? 8 : arr->cap * 2);
+ arr->d = RENEW_ARR(S, arr->d, Val, arr->cap, newsz);
+ arr->cap = newsz;
+ }
+ arr->d[arr->len++] = v;
+}
+void objarr_put(State *S, ObjArr *arr, size_t ix, Val v) {
+ CHECK(ix <= arr->len, "array index out of bounds");
+ if (ix == arr->len) {
+ objarr_append(S, arr, v);
+ } else {
+ arr->d[ix] = v;
+ }
+}
+
+static void print_val_h(Val v, int depth);
+void print_val(Val v) {
+ print_val_h(v, 8);
+}
+static void print_val_h(Val v, int depth) {
switch (v.ty) {
case TY_NIL:
printf("nil");
@@ -72,12 +106,25 @@ void print_val(Val v) {
printf("%s", AS_CSTRING(v));
break;
case OTY_FUNC:
- printf("[function Function]");
+ printf("<func>");
+ break;
+ case OTY_ARR:;
+ ObjArr *a = AS_ARR(v);
+ if (depth <= 0)
+ printf("<arr>");
+ else {
+ printf("[ ");
+ for (int i = 0; i < a->len; i++) {
+ print_val_h(a->d[i], depth-1);
+ printf(" ");
+ }
+ printf("]");
+ }
break;
}
break;
case TY_CFUNC:
- printf("[cfunc]");
+ printf("<cfunc>");
break;
}
}
@@ -116,6 +163,7 @@ const char *typename_str(Val v) {
switch (AS_OBJ(v)->oty) {
case OTY_STRING: return "String";
case OTY_FUNC: return "Func";
+ case OTY_ARR: return "Arr";
}
break;
case TY_CFUNC: return "cfunc";