feat: add subscript operator for array indexing and string character access

Implement the `[]` subscript operator as an infix parser at `PREC_CALL` precedence, compiling to a method call on the receiver. Add a `string_subscript` primitive that handles integer indices (including negative for reverse indexing), returns `null` for out-of-bounds or non-integer arguments, and returns a one-character string. Register the `[ ]` method on the string class and include tests for basic indexing, negative indices, out-of-bounds, wrong types, and non-integer indices.
This commit is contained in:
Bob Nystrom
2013-11-24 18:45:07 +00:00
parent cc55fd2a57
commit 2490e6a425
3 changed files with 93 additions and 2 deletions
+24
View File
@@ -0,0 +1,24 @@
// Returns characters (as strings).
io.write("abcd"[0]) // expect: a
io.write("abcd"[1]) // expect: b
io.write("abcd"[2]) // expect: c
io.write("abcd"[3]) // expect: d
// Allows indexing backwards from the end.
io.write("abcd"[-4]) // expect: a
io.write("abcd"[-3]) // expect: b
io.write("abcd"[-2]) // expect: c
io.write("abcd"[-1]) // expect: d
// Handle out of bounds.
// TODO(bob): Should halt the fiber or raise an error somehow.
io.write("abcd"[4]) // expect: null
io.write("abcd"[-5]) // expect: null
// Handle wrong argument type.
// TODO(bob): Should halt the fiber or raise an error somehow.
io.write("abcd"[true]) // expect: null
// Handle non-integer index.
// TODO(bob): Should halt the fiber or raise an error somehow.
io.write("abcd"[1.5]) // expect: null