arrays + builtins
This commit is contained in:
@@ -97,6 +97,23 @@ func Eval(node ast.Node, env *object.Environment) object.Object {
|
||||
case *ast.StringLiteral:
|
||||
return &object.String{Value: node.Value}
|
||||
|
||||
case *ast.ArrayLiteral:
|
||||
elements := evalExpressions(node.Elements, env)
|
||||
if len(elements) == 1 && isError(elements[0]) {
|
||||
return elements[0]
|
||||
}
|
||||
return &object.Array{Elements: elements}
|
||||
|
||||
case *ast.IndexExpression:
|
||||
left := Eval(node.Left, env)
|
||||
if isError(left) {
|
||||
return left
|
||||
}
|
||||
index := Eval(node.Index, env)
|
||||
if isError(index) {
|
||||
return index
|
||||
}
|
||||
return evalIndexExpression(left, index)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -323,3 +340,24 @@ func unwrapReturnValue(obj object.Object) object.Object {
|
||||
|
||||
return obj
|
||||
}
|
||||
|
||||
func evalIndexExpression(left, index object.Object) object.Object {
|
||||
switch {
|
||||
case left.Type() == object.ARRAY_OBJ && index.Type() == object.INTEGER_OBJ:
|
||||
return evalArrayIndexExpression(left, index)
|
||||
default:
|
||||
return newError("index operator not supported: %s", left.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func evalArrayIndexExpression(array, index object.Object) object.Object {
|
||||
arrayObject := array.(*object.Array)
|
||||
idx := index.(*object.Integer).Value
|
||||
maxInx := int64(len(arrayObject.Elements) - 1)
|
||||
|
||||
if idx < 0 || idx > maxInx {
|
||||
return NULL
|
||||
}
|
||||
|
||||
return arrayObject.Elements[idx]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user