-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgluayaml.go
68 lines (59 loc) · 1.32 KB
/
gluayaml.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
package gluayaml
import (
"github.com/yuin/gopher-lua"
"gopkg.in/yaml.v2"
)
func Loader(L *lua.LState) int {
tb := L.NewTable()
L.SetFuncs(tb, map[string]lua.LGFunction{
"parse": apiParse,
"dump": apiDump,
})
L.Push(tb)
return 1
}
// apiParse parses yaml formatted text to the table.
func apiParse(L *lua.LState) int {
str := L.CheckString(1)
var value interface{}
err := yaml.Unmarshal([]byte(str), &value)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
L.Push(fromYAML(L, value))
return 1
}
// apiDump dumps the yaml formatted text.
func apiDump(L *lua.LState) int {
L.RaiseError("unimplemented function")
return 0
}
func fromYAML(L *lua.LState, value interface{}) lua.LValue {
switch converted := value.(type) {
case bool:
return lua.LBool(converted)
case float64:
return lua.LNumber(converted)
case int:
return lua.LNumber(converted)
case string:
return lua.LString(converted)
case []interface{}:
arr := L.CreateTable(len(converted), 0)
for _, item := range converted {
arr.Append(fromYAML(L, item))
}
return arr
case map[interface{}]interface{}:
tbl := L.CreateTable(0, len(converted))
for key, item := range converted {
if s, ok := key.(string); ok {
tbl.RawSetH(lua.LString(s), fromYAML(L, item))
}
}
return tbl
}
return lua.LNil
}