Skip to content

Commit

Permalink
List; add swap(index0, index1)
Browse files Browse the repository at this point in the history
  • Loading branch information
ruby0x1 committed Dec 3, 2020
1 parent 6200987 commit 38f50fe
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
11 changes: 11 additions & 0 deletions doc/site/modules/core/list.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<pre class="snippet">
var list = [0, 1, 2, 3, 4]
list.swap(0, 3)
System.print(list) //> [3, 1, 2, 0, 4]
</pre>

### **[**index**]** operator

Gets the element at `index`. If `index` is negative, it counts backwards from
Expand Down
16 changes: 16 additions & 0 deletions src/vm/wren_core.c
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down Expand Up @@ -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);
Expand Down
9 changes: 9 additions & 0 deletions test/core/list/swap.wren
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit 38f50fe

Please sign in to comment.