From d3616b07b2a4388dcf66e2664c4627d884673205 Mon Sep 17 00:00:00 2001 From: Kayne Ruse Date: Mon, 25 May 2026 12:05:10 +1000 Subject: [PATCH] Added table support to for loops --- scripts/hello_world.toy | 16 +++++++++++++++- source/toy_vm.c | 28 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/scripts/hello_world.toy b/scripts/hello_world.toy index 5614168..296d960 100644 --- a/scripts/hello_world.toy +++ b/scripts/hello_world.toy @@ -1,6 +1,20 @@ -var table = ["alpha": 1, "beta": 2]; +var table = [ + "Alpha": 1, + "Bravo": 2, + "Charlie": 3, + "Delta": 4, + "Echo": 5, + "Foxtrot": 6, + "Golf": 7, + "Hotel": 8, + "India": 9, + "Juliett": 10, + "Kilo": 11, + "Lima": 12, + "Mike": 13, +]; for (var i in table) { print i; diff --git a/source/toy_vm.c b/source/toy_vm.c index 96bfac1..fad5bf8 100644 --- a/source/toy_vm.c +++ b/source/toy_vm.c @@ -517,6 +517,34 @@ static void processIterate(Toy_VM* vm) { Toy_pushStack(&vm->stack, TOY_VALUE_FROM_INTEGER(index + 1)); Toy_pushStack(&vm->stack, value); } + else if (TOY_VALUE_IS_TABLE(compound)) { + Toy_Table* table = TOY_VALUE_AS_TABLE(compound); + unsigned int index = (unsigned int)TOY_VALUE_AS_INTEGER(counter); + + //loop to the next element + while(index < table->capacity) { + //is this a useable element + if (!TOY_VALUE_IS_NULL(table->data[index].key)) { + break; + } + + index++; + } + + //return the compound & counter to the stack + Toy_pushStack(&vm->stack, compound); + Toy_pushStack(&vm->stack, TOY_VALUE_FROM_INTEGER(index + 1)); + + //if something was found, push it and return + if (index < table->capacity) { + Toy_pushStack(&vm->stack, Toy_copyValue(&vm->memoryBucket, table->data[index].value)); + } + else { + //otherwise force a jump then exit + Toy_pushStack(&vm->stack, TOY_VALUE_FROM_NULL()); + processJump(vm); + } + } else { fprintf(stderr, TOY_CC_ERROR "ERROR: Unknown iterable type '%s' found in for loop, exiting\n" TOY_CC_RESET, Toy_getValueTypeAsCString(Toy_unwrapValue(compound).type)); exit(-1);