-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathdecoder.go
77 lines (67 loc) · 1.73 KB
/
decoder.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 (
jsonDecoderType = "json.Decoder"
)
func CheckJSONDecoder(L *lua.LState, n int) *json.Decoder {
ud := L.CheckUserData(n)
if decoder, ok := ud.Value.(*json.Decoder); ok {
return decoder
}
L.ArgError(n, jsonDecoderType+" expected")
return nil
}
func LVJSONDecoder(L *lua.LState, decoder *json.Decoder) lua.LValue {
ud := L.NewUserData()
ud.Value = decoder
L.SetMetatable(ud, L.GetTypeMetatable(jsonDecoderType))
return ud
}
func jsonDecoderDecode(L *lua.LState) int {
decoder := CheckJSONDecoder(L, 1)
L.Pop(L.GetTop())
var value interface{}
if err := decoder.Decode(&value); err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
L.Push(decode(L, value))
return 1
}
func jsonDecoderInputOffset(L *lua.LState) int {
decoder := CheckJSONDecoder(L, 1)
L.Pop(L.GetTop())
L.Push(lua.LNumber(decoder.InputOffset()))
return 1
}
func jsonDecoderMore(L *lua.LState) int {
decoder := CheckJSONDecoder(L, 1)
L.Pop(L.GetTop())
L.Push(lua.LBool(decoder.More()))
return 1
}
func registerDecoder(L *lua.LState) {
mt := L.NewTypeMetatable(jsonDecoderType)
L.SetGlobal(jsonDecoderType, mt)
L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{
"decode": jsonDecoderDecode,
"input_offset": jsonDecoderInputOffset,
"more": jsonDecoderMore,
}))
}
func registerJsonDecodedObject(L *lua.LState) {
mt := L.NewTypeMetatable(jsonTableIsObject)
mt.RawSetString(jsonTableIsObject, lua.LTrue)
}
func newJSONDecoder(L *lua.LState) int {
reader := io.CheckIOReader(L, 1)
L.Pop(L.GetTop())
decoder := json.NewDecoder(reader)
L.Push(LVJSONDecoder(L, decoder))
return 1
}