/
goluacnf.go
85 lines (64 loc) · 1.58 KB
/
goluacnf.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
package goluacnf
import (
"errors"
"github.com/yuin/gluamapper"
"github.com/yuin/gopher-lua"
)
var Pool Config
type Config struct {
data Data
tbl *lua.LTable
}
type Data map[interface{}]interface{}
func (c *Config) GetData() Data {
return c.data
}
func (c *Config) Get(key string) interface{} {
return c.GetData()[string(key)]
}
func (c *Config) String(key string) string {
return c.Get(key).(string)
}
func (c *Config) Int(key string) int {
return int(c.Get(key).(float64))
}
func (c *Config) Int64(key string) int64 {
return int64(c.Int(key))
}
func (c *Config) Float(key string) float64 {
return c.Get(key).(float64)
}
func (c *Config) Float32(key string) float32 {
return float32(c.Float(key))
}
func (c *Config) Bool(key string) bool {
return c.Get(key).(bool)
}
func (c *Config) Map(st interface{}) error {
return gluamapper.Map(c.tbl, st)
}
func NewConfig(table *lua.LTable) (Config, error) {
mp, err := mapper(table)
if err != nil {
return Config{}, err
}
return Config{data: mp, tbl: table}, nil
}
func Register(filepath, environ string) (Config, error) {
L := lua.NewState()
defer L.Close()
if err := L.DoFile(filepath); err != nil {
return Config{}, err
}
cnf, err := NewConfig(L.GetGlobal(environ).(*lua.LTable))
Pool = cnf
return cnf, err
}
func mapper(tbl *lua.LTable) (map[interface{}]interface{}, error) {
opt := gluamapper.Option{NameFunc: gluamapper.ToUpperCamelCase}
mp, ok := gluamapper.ToGoValue(tbl, opt).(map[interface{}]interface{})
if !ok {
return nil, errors.New("arguments #1 must be a table, but got an array")
}
return mp, nil
}