Skip to content

Commit

Permalink
Merge pull request #104 from skx/102-index-number
Browse files Browse the repository at this point in the history
Ensure we have integer for string index-expression.
  • Loading branch information
skx authored Dec 5, 2023
2 parents 2835a28 + 279909c commit 7b31b27
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 8 deletions.
13 changes: 9 additions & 4 deletions evaluator/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -1154,17 +1154,22 @@ func evalHashIndexExpression(hash, index object.Object) object.Object {

func evalStringIndexExpression(input, index object.Object) object.Object {
str := input.(*object.String).Value
idx := index.(*object.Integer).Value
idx, isInt := index.(*object.Integer)
if !isInt {
return newError("expected an integer for string index, got something else")
}

i := idx.Value
max := int64(len(str))
if idx < 0 || idx > max {
return NULL
if i < 0 || i > max {
return newError("index out of bounds")
}

// Get the characters as an array of runes
chars := []rune(str)

// Now index
ret := chars[idx]
ret := chars[i]

// And return as a string.
return &object.String{Value: string(ret)}
Expand Down
34 changes: 30 additions & 4 deletions evaluator/evaluator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -458,40 +458,66 @@ func TestStringIndexExpression(t *testing.T) {
tests := []struct {
input string
expected interface{}
err bool
}{
{
"\"Steve\"[0]",
"S",
false,
},
{
"\"Steve\"[1]",
"t",
false,
},
{
"\"Steve\"[101]",
nil,
true,
},
{
"\"Steve\"[-1]",
nil,
true,
},
{
"\"狐犬\"[0]",
"狐",
false,
},
{
"\"狐犬\"[1]",
"犬",
false,
},
{
"\"狐犬\"[\"x\"]",
"",
true,
},
{
"\"狐犬\"[-3]",
"",
true,
},
}
for _, tt := range tests {
evaluated := testEval(tt.input)

str, ok := tt.expected.(string)
if ok {
testStringObject(t, evaluated, str)
_, err := evaluated.(*object.Error)

if err {
if tt.err == false {
t.Fatalf("expected error for input '%s', got %T", tt.input, evaluated)
}
} else {
testNullObject(t, evaluated)
str, ok := tt.expected.(string)
if ok {
testStringObject(t, evaluated, str)
} else {

testNullObject(t, evaluated)
}
}
}
}
Expand Down

0 comments on commit 7b31b27

Please sign in to comment.