Skip to content

Commit

Permalink
script.Add accepts a CallableFunc value (#124)
Browse files Browse the repository at this point in the history
* script.Add accepts a CallableFunc value

* moved to FromInterface
  • Loading branch information
geseq authored and d5 committed Mar 1, 2019
1 parent 306055a commit 880ee04
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
4 changes: 4 additions & 0 deletions objects/conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,10 @@ func FromInterface(v interface{}) (Object, error) {
return &Time{Value: v}, nil
case Object:
return v, nil
case CallableFunc:
return &UserFunction{Value: v}, nil
case func(...Object) (Object, error):
return &UserFunction{Value: v}, nil
}

return nil, fmt.Errorf("cannot convert to object: %T", v)
Expand Down
14 changes: 13 additions & 1 deletion script/script_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,26 @@ import (
)

func TestScript_Add(t *testing.T) {
s := script.New([]byte(`a := b`))
s := script.New([]byte(`a := b; c := test(b); d := test(5)`))
assert.NoError(t, s.Add("b", 5)) // b = 5
assert.NoError(t, s.Add("b", "foo")) // b = "foo" (re-define before compilation)
assert.NoError(t, s.Add("test", func(args ...objects.Object) (ret objects.Object, err error) {
if len(args) > 0 {
switch arg := args[0].(type) {
case *objects.Int:
return &objects.Int{Value: arg.Value + 1}, nil
}
}

return &objects.Int{Value: 0}, nil
}))
c, err := s.Compile()
assert.NoError(t, err)
assert.NoError(t, c.Run())
assert.Equal(t, "foo", c.Get("a").Value())
assert.Equal(t, "foo", c.Get("b").Value())
assert.Equal(t, int64(0), c.Get("c").Value())
assert.Equal(t, int64(6), c.Get("d").Value())
}

func TestScript_Remove(t *testing.T) {
Expand Down

0 comments on commit 880ee04

Please sign in to comment.