From f7babd33e3d755453c3751b9592376609da9028c Mon Sep 17 00:00:00 2001 From: Flipez Date: Wed, 29 Sep 2021 00:02:49 +0200 Subject: [PATCH] add support for index operator on string Signed-off-by: Flipez --- evaluator/evaluator.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/evaluator/evaluator.go b/evaluator/evaluator.go index 6346296..74c757d 100644 --- a/evaluator/evaluator.go +++ b/evaluator/evaluator.go @@ -174,11 +174,25 @@ func evalIndexExpression(left, index object.Object) object.Object { return evalArrayIndexExpression(left, index) case left.Type() == object.HASH_OBJ: return evalHashIndexExpression(left, index) + case left.Type() == object.STRING_OBJ: + return evalStringIndexExpression(left, index) default: return newError("index operator not supported: %s", left.Type()) } } +func evalStringIndexExpression(left, index object.Object) object.Object { + stringObject := left.(*object.String) + idx := index.(*object.Integer).Value + max := int64(len(stringObject.Value) - 1) + + if idx < 0 || idx > max { + return NULL + } + + return &object.String{Value: string(stringObject.Value[idx])} +} + func evalHashIndexExpression(hash, index object.Object) object.Object { hashObject := hash.(*object.Hash) key, ok := index.(object.Hashable)