Allow [0..-1] and [0...0] to work on empty lists.

This commit is contained in:
Bob Nystrom
2014-02-14 20:10:41 -08:00
parent ca7ff222fe
commit ea3cfa05bd
3 changed files with 18 additions and 8 deletions

View File

@ -10,10 +10,7 @@ class List {
}
+ that {
var result = []
for (element in this) {
result.add(element)
}
var result = this[0..-1]
for (element in that) {
result.add(element)
}

View File

@ -53,10 +53,7 @@ static const char* libSource =
" }\n"
"\n"
" + that {\n"
" var result = []\n"
" for (element in this) {\n"
" result.add(element)\n"
" }\n"
" var result = this[0..-1]\n"
" for (element in that) {\n"
" result.add(element)\n"
" }\n"
@ -389,6 +386,18 @@ DEF_NATIVE(list_subscript)
ObjRange* range = AS_RANGE(args[1]);
// TODO: This code is pretty hairy. Is there a more elegant way?
// Corner case: an empty range at zero is allowed on an empty list.
// This way, list[0..-1] and list[0...list.count] can be used to copy a list
// even when empty.
if (list->count == 0) {
if ((range->from == 0 && range->to == -1 && range->isInclusive) ||
(range->from == 0 && range->to == 0 && !range->isInclusive))
{
RETURN_OBJ(wrenNewList(vm, 0));
}
}
int from = validateIndexValue(vm, args, list->count, range->from,
"Range start");
if (from == -1) return PRIM_ERROR;

View File

@ -29,3 +29,7 @@ IO.print(list[1..-2]) // expect: [b, c, d]
IO.print(list[2...-1]) // expect: [c, d]
IO.print(list[4..-5]) // expect: [e, d, c, b, a]
IO.print(list[3...-6]) // expect: [d, c, b, a]
// An empty range at zero is allowed on an empty list.
IO.print([][0...0]) // expect: []
IO.print([][0..-1]) // expect: []