feat: implement subscript operator for lists with negative index and bounds checking
Add list_subscript primitive that supports integer indexing with negative indices counting from the end, returns null for out-of-bounds access, non-integer indices, and non-numeric argument types. Register the `[ ]` operator on the List class in loadCore and include comprehensive test coverage in test/list_subscript.wren.
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
// Returns elements.
|
||||
var list = ["a", "b", "c", "d"]
|
||||
io.write(list[0]) // expect: a
|
||||
io.write(list[1]) // expect: b
|
||||
io.write(list[2]) // expect: c
|
||||
io.write(list[3]) // expect: d
|
||||
|
||||
// Allows indexing backwards from the end.
|
||||
io.write(list[-4]) // expect: a
|
||||
io.write(list[-3]) // expect: b
|
||||
io.write(list[-2]) // expect: c
|
||||
io.write(list[-1]) // expect: d
|
||||
|
||||
// Handle out of bounds.
|
||||
// TODO(bob): Should halt the fiber or raise an error somehow.
|
||||
io.write(list[4]) // expect: null
|
||||
io.write(list[-5]) // expect: null
|
||||
|
||||
// Handle wrong argument type.
|
||||
// TODO(bob): Should halt the fiber or raise an error somehow.
|
||||
io.write(list[true]) // expect: null
|
||||
|
||||
// Handle non-integer index.
|
||||
// TODO(bob): Should halt the fiber or raise an error somehow.
|
||||
io.write(list[1.5]) // expect: null
|
||||
Reference in New Issue
Block a user