Skip to content

Commit bda181a

Browse files
committed
4.4 Arrays (evaluating array literals)
1 parent 375deda commit bda181a

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

evaluator/evaluator.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,13 @@ func Eval(node ast.Node, env *object.Environment) object.Object {
125125

126126
// Call the function. Apply the function to the arguments.
127127
return applyFunction(function, args)
128+
129+
case *ast.ArrayLiteral:
130+
elements := evalExpressions(node.Elements, env)
131+
if len(elements) == 1 && isError(elements[0]) {
132+
return elements[0]
133+
}
134+
return &object.Array{Elements: elements}
128135
}
129136

130137
return nil

evaluator/evaluator_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,25 @@ func TestBuiltinFunctions(t *testing.T) {
402402
}
403403
}
404404

405+
func TestArrayLiterals(t *testing.T) {
406+
input := "[1, 2 * 2, 3 + 3]"
407+
408+
evaluated := testEval(input)
409+
result, ok := evaluated.(*object.Array)
410+
if !ok {
411+
t.Fatalf("object is not Array. got=%T (%+v)", evaluated, evaluated)
412+
}
413+
414+
if len(result.Elements) != 3 {
415+
t.Fatalf("array has wrong num of elements. got=%d",
416+
len(result.Elements))
417+
}
418+
419+
testIntegerObject(t, result.Elements[0], 1)
420+
testIntegerObject(t, result.Elements[1], 4)
421+
testIntegerObject(t, result.Elements[2], 6)
422+
}
423+
405424
func testEval(input string) object.Object {
406425
l := lexer.New(input)
407426
p := parser.New(l)

object/object.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ const (
3636

3737
// BUILTIN_OBJ is the Builtin object type.
3838
BUILTIN_OBJ = "BUILTIN"
39+
40+
// ARRAY_OBJECT is the Array object type.
41+
ARRAY_OBJ = "ARRAY"
3942
)
4043

4144
// BuiltinFunction represents the builtin function type.
@@ -175,3 +178,27 @@ func (b *Builtin) Type() ObjectType { return BUILTIN_OBJ }
175178

176179
// Inspect returns a stringified version of the object for debugging.
177180
func (b *Builtin) Inspect() string { return "builtin function" }
181+
182+
// Array is the array literal type that holds a slice of Object(s).
183+
type Array struct {
184+
Elements []Object
185+
}
186+
187+
// Type returns the type of the object
188+
func (ao *Array) Type() ObjectType { return ARRAY_OBJ }
189+
190+
// Inspect returns a stringified version of the object for debugging.
191+
func (ao *Array) Inspect() string {
192+
var out bytes.Buffer
193+
194+
elements := []string{}
195+
for _, e := range ao.Elements {
196+
elements = append(elements, e.Inspect())
197+
}
198+
199+
out.WriteString("[")
200+
out.WriteString(strings.Join(elements, ", "))
201+
out.WriteString("]")
202+
203+
return out.String()
204+
}

0 commit comments

Comments
 (0)