diff --git a/doc/site/modules/core/list.markdown b/doc/site/modules/core/list.markdown index 94857c92..a4060abe 100644 --- a/doc/site/modules/core/list.markdown +++ b/doc/site/modules/core/list.markdown @@ -127,6 +127,17 @@ System.print(list) //> [6, 7, 8, 9] It is a runtime error if `comparer` is not a function. +### **swap**(index0, index1) + +Swaps values inside the list around. Puts the value from `index0` in `index1`, +and the value from `index1` at `index0` in the list. + +
+var list = [0, 1, 2, 3, 4] +list.swap(0, 3) +System.print(list) //> [3, 1, 2, 0, 4] ++ ### **[**index**]** operator Gets the element at `index`. If `index` is negative, it counts backwards from diff --git a/src/vm/wren_core.c b/src/vm/wren_core.c index d9450b62..9de1bf56 100644 --- a/src/vm/wren_core.c +++ b/src/vm/wren_core.c @@ -400,6 +400,21 @@ DEF_PRIMITIVE(list_indexOf) RETURN_NUM(wrenListIndexOf(vm, list, args[1])); } +DEF_PRIMITIVE(list_swap) +{ + ObjList* list = AS_LIST(args[0]); + uint32_t indexA = validateIndex(vm, args[1], list->elements.count, "Index 0"); + if (indexA == UINT32_MAX) return false; + uint32_t indexB = validateIndex(vm, args[2], list->elements.count, "Index 1"); + if (indexB == UINT32_MAX) return false; + + Value a = list->elements.data[indexA]; + list->elements.data[indexA] = list->elements.data[indexB]; + list->elements.data[indexB] = a; + + RETURN_NULL; +} + DEF_PRIMITIVE(list_subscript) { ObjList* list = AS_LIST(args[0]); @@ -1367,6 +1382,7 @@ void wrenInitializeCore(WrenVM* vm) PRIMITIVE(vm->listClass, "iteratorValue(_)", list_iteratorValue); PRIMITIVE(vm->listClass, "removeAt(_)", list_removeAt); PRIMITIVE(vm->listClass, "indexOf(_)", list_indexOf); + PRIMITIVE(vm->listClass, "swap(_,_)", list_swap); vm->mapClass = AS_CLASS(wrenFindVariable(vm, coreModule, "Map")); PRIMITIVE(vm->mapClass->obj.classObj, "new()", map_new); diff --git a/test/core/list/swap.wren b/test/core/list/swap.wren new file mode 100644 index 00000000..a2cf31e5 --- /dev/null +++ b/test/core/list/swap.wren @@ -0,0 +1,9 @@ +var list = [0, 1, 2, 3, 4] + +list.swap(0, 3) +System.print(list) // expect: [3, 1, 2, 0, 4] + +list.swap(-1, 2) +System.print(list) // expect: [3, 1, 4, 0, 2] + +list.swap(8, 0) // expect runtime error: Index 0 out of bounds. \ No newline at end of file