Advanced features

How to add your functions to the standard library

When using Gentee in other projects, it may be necessary to expand the standard library. The Customize function allows you to add any number of go-functions to the standard library and use them in scripts. It should be noted that in this case the scripts will not be compiled by the original compiler, since there will be no added functions there. The Customize function must be called before calling other functions from the gentee package.
To expand the standard library, you should specify an array of functions in the parameter of the Custom type. Each function is described by the structure EmbedItem, in which a prototype in the Gentee language and the function itself are specified. The function may return a value of the error type and have a variable number of parameters.

Type correspondence

Parameters and return value of go-functions must have types in accordance with this table. When using core types, you must import github.com/gentee/gentee/core.
Gentee type
Golang type
int
int64
bool
int64
char
int64
thread
int64
float
float64
str
string
arr
*core.Array
buf
*core.Buffer
map
*core.Map
set
*core.Set
struct type
*core.Struct
obj
*core.Obj
1
func sum(x, y int64) int64 {
2
return x + 2*y
3
}
4
5
func varInt(init int64, pars ...int64) int64 {
6
for _, i := range pars {
7
init += i
8
}
9
return init
10
}
11
12
func shortLen(s string) (int64, error) {
13
if len(s) < 10 {
14
return len(s), nil
15
}
16
return 0, fmt.Errorf("string %s is too long", s)
17
}
18
19
func main() {
20
var customLib = []gentee.EmbedItem{
21
{Prototype: `sum(int,int) int`, Object: sum},
22
{Prototype: `InitSum(int) int`, Object: varInt},
23
{Prototype: `ShortLen(str) int`, Object: shortLen},
24
}
25
err := gentee.Customize(&gentee.Custom{
26
Embedded: customLib,
27
})
28
if err != nil {
29
log.Fatal(err)
30
}
31
workspace := gentee.New()
32
exec, _, err := workspace.Compile(`run {
33
Println("Sum = %{sum(10, 6)}")
34
Println("InitSum = " + InitSum(4, 67, 4, 22))
35
ShortLen("this string is too long")
36
}`, ``)
37
...
38
}
Copied!
Last modified 1yr ago