-
Notifications
You must be signed in to change notification settings - Fork 3
/
doc_test.go
106 lines (84 loc) · 1.63 KB
/
doc_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package binder
import (
"errors"
"log"
)
func ExampleBinder_Func() {
b := New(Options{
SkipOpenLibs: true,
})
b.Func("log", func(c *Context) error {
t := c.Top()
if t == 0 {
return errors.New("need arguments")
}
l := []interface{}{}
for i := 1; i <= t; i++ {
l = append(l, c.Arg(i).Any())
}
log.Println(l...)
return nil
})
if err := b.DoString(`
log('This', 'is', 'Lua')
`); err != nil {
log.Fatalln(err)
}
}
func ExampleBinder_Module() {
b := New()
m := b.Module("reverse")
m.Func("string", func(c *Context) error {
if c.Top() == 0 {
return errors.New("need arguments")
}
s := c.Arg(1).String()
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
c.Push().String(string(runes))
return nil
})
if err := b.DoString(`
local r = require('reverse')
print(r.string('ABCDEFGHIJKLMNOPQRSTUFVWXYZ'))
`); err != nil {
log.Fatalln(err)
}
}
func ExampleBinder_Table() {
type Person struct {
Name string
}
b := New()
t := b.Table("person")
t.Static("new", func(c *Context) error {
if c.Top() == 0 {
return errors.New("need arguments")
}
n := c.Arg(1).String()
c.Push().Data(&Person{n}, "person")
return nil
})
t.Dynamic("name", func(c *Context) error {
p, ok := c.Arg(1).Data().(*Person)
if !ok {
return errors.New("person expected")
}
if c.Top() == 1 {
c.Push().String(p.Name)
} else {
p.Name = c.Arg(2).String()
}
return nil
})
if err := b.DoString(`
local p = person.new('Steeve')
print(p:name())
p:name('Alice')
print(p:name())
`); err != nil {
log.Fatalln(err)
}
}