Adds range subscripting for strings.

This commit is contained in:
Gavin Schulz
2015-01-18 22:55:30 -08:00
parent f79f1d2b63
commit bfc2f9c0ee
12 changed files with 156 additions and 40 deletions
+1 -1
View File
@@ -1,2 +1,2 @@
var a = "123"
a["2"] // expect runtime error: Subscript must be a number.
a["2"] // expect runtime error: Subscript must be a number or a range.
+34
View File
@@ -0,0 +1,34 @@
var string = "abcde"
IO.print(string[0..0]) // expect: a
IO.print(string[1...1] == "") // expect: true
IO.print(string[1..2]) // expect: bc
IO.print(string[1...2]) // expect: b
IO.print(string[2..4]) // expect: cde
IO.print(string[2...5]) // expect: cde
// A backwards range reverses.
IO.print(string[3..1]) // expect: dcb
IO.print(string[3...1]) // expect: dc
IO.print(string[3...3] == "") // expect: true
// Negative ranges index from the end.
IO.print(string[-5..-2]) // expect: abcd
IO.print(string[-5...-2]) // expect: abc
IO.print(string[-3..-5]) // expect: cba
IO.print(string[-3...-6]) // expect: cba
// Half-negative ranges are treated like the negative value is fixed before
// walking the range.
IO.print(string[-5..3]) // expect: abcd
IO.print(string[-3...5]) // expect: cde
IO.print(string[-2..1]) // expect: dcb
IO.print(string[-2...0]) // expect: dcb
IO.print(string[1..-2]) // expect: bcd
IO.print(string[2...-1]) // expect: cd
IO.print(string[4..-5]) // expect: edcba
IO.print(string[3...-6]) // expect: dcba
// An empty range at zero is allowed on an empty string.
IO.print(""[0...0] == "") // expect: true
IO.print(""[0..-1] == "") // expect: true
@@ -0,0 +1,2 @@
var a = "string"
a[1.5..2] // expect runtime error: Range start must be an integer.
@@ -0,0 +1,2 @@
var a = "123"
a[3..2] // expect runtime error: Range start out of bounds.
@@ -0,0 +1,2 @@
var a = "123"
a[-4..2] // expect runtime error: Range start out of bounds.
@@ -0,0 +1,2 @@
var a = "123"
a[1...4] // expect runtime error: Range end out of bounds.
@@ -0,0 +1,2 @@
var a = "123"
a[0...-5] // expect runtime error: Range end out of bounds.
@@ -0,0 +1,2 @@
var a = "string"
a[1..2.5] // expect runtime error: Range end must be an integer.
@@ -0,0 +1,2 @@
var a = "123"
a[1..3] // expect runtime error: Range end out of bounds.
@@ -0,0 +1,2 @@
var a = "123"
a[0..-4] // expect runtime error: Range end out of bounds.