-
Notifications
You must be signed in to change notification settings - Fork 39
/
encoder.go
77 lines (68 loc) · 1.7 KB
/
encoder.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
package json
import (
"encoding/json"
"github.com/vadv/gopher-lua-libs/io"
lua "github.com/yuin/gopher-lua"
)
const (
jsonEncoderType = "json.Encoder"
)
func CheckJSONEncoder(L *lua.LState, n int) *json.Encoder {
ud := L.CheckUserData(n)
if encoder, ok := ud.Value.(*json.Encoder); ok {
return encoder
}
L.ArgError(n, jsonEncoderType+" expected")
return nil
}
func LVJSONEncoder(L *lua.LState, encoder *json.Encoder) lua.LValue {
ud := L.NewUserData()
ud.Value = encoder
L.SetMetatable(ud, L.GetTypeMetatable(jsonEncoderType))
return ud
}
func jsonEncoderEncode(L *lua.LState) int {
encoder := CheckJSONEncoder(L, 1)
value := L.CheckAny(2)
L.Pop(L.GetTop())
err := encoder.Encode(jsonValue{
LValue: value,
visited: make(map[*lua.LTable]bool),
})
if err != nil {
L.Push(lua.LString(err.Error()))
return 1
}
return 0
}
func jsonEncoderSetIndent(L *lua.LState) int {
encoder := CheckJSONEncoder(L, 1)
prefix := L.CheckString(2)
indent := L.CheckString(3)
L.Pop(L.GetTop())
encoder.SetIndent(prefix, indent)
return 0
}
func jsonEncoderSetEscapeHTML(L *lua.LState) int {
encoder := CheckJSONEncoder(L, 1)
on := L.CheckBool(2)
L.Pop(L.GetTop())
encoder.SetEscapeHTML(on)
return 0
}
func registerJSONEncoder(L *lua.LState) {
mt := L.NewTypeMetatable(jsonEncoderType)
L.SetGlobal(jsonEncoderType, mt)
L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{
"encode": jsonEncoderEncode,
"set_indent": jsonEncoderSetIndent,
"set_escape_HTML": jsonEncoderSetEscapeHTML,
}))
}
func newJSONEncoder(L *lua.LState) int {
writer := io.CheckIOWriter(L, 1)
L.Pop(L.GetTop())
encoder := json.NewEncoder(writer)
L.Push(LVJSONEncoder(L, encoder))
return 1
}