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:
@@ -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
|
||||
Reference in New Issue
Block a user