mirror of
https://github.com/wren-lang/wren.git
synced 2026-01-10 21:58:48 +01:00
List; add swap(index0, index1)
This commit is contained in:
@ -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
|
||||
|
||||
@ -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);
|
||||
|
||||
9
test/core/list/swap.wren
Normal file
9
test/core/list/swap.wren
Normal file
@ -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.
|
||||
Reference in New Issue
Block a user