mapserver/server/luaparser/luaparser.go

97 lines
1.6 KiB
Go
Raw Normal View History

2019-02-08 15:24:54 +03:00
package luaparser
import (
2019-02-08 18:02:24 +03:00
"errors"
"github.com/yuin/gopher-lua"
"strconv"
2019-02-08 15:24:54 +03:00
)
func New() *LuaParser {
2019-02-08 18:02:24 +03:00
p := LuaParser{
state: lua.NewState(lua.Options{SkipOpenLibs: true}),
}
2019-02-08 15:24:54 +03:00
2019-02-08 18:02:24 +03:00
return &p
2019-02-08 15:24:54 +03:00
}
type LuaParser struct {
2019-02-08 18:02:24 +03:00
state *lua.LState
2019-02-08 15:24:54 +03:00
}
2019-02-22 15:55:11 +03:00
func parseMap(t *lua.LTable) map[string]interface{} {
2019-02-08 18:02:24 +03:00
result := make(map[string]interface{})
2019-02-22 15:55:11 +03:00
t.ForEach(func(k1, v1 lua.LValue) {
boolValue, ok := v1.(lua.LBool)
if ok {
result[k1.String()] = boolValue == lua.LTrue
}
intValue, ok := v1.(lua.LNumber)
if ok {
result[k1.String()], _ = strconv.Atoi(intValue.String())
}
strValue, ok := v1.(lua.LString)
if ok {
result[k1.String()] = strValue.String()
}
tblValue, ok := v1.(*lua.LTable)
if ok {
result[k1.String()] = parseMap(tblValue)
}
})
return result
}
2019-02-22 15:57:33 +03:00
func (this *LuaParser) ParseList(expr string) ([]map[string]interface{}, error) {
2019-02-22 15:55:11 +03:00
result := make([]map[string]interface{}, 0)
2019-02-08 18:02:24 +03:00
err := this.state.DoString(expr)
if err != nil {
return result, err
}
lv := this.state.Get(-1)
tbl, ok := lv.(*lua.LTable)
if !ok {
return result, errors.New("parsing failed")
}
tbl.ForEach(func(k, v lua.LValue) {
2019-02-22 15:55:11 +03:00
key, ok := v.(*lua.LTable)
2019-02-08 18:02:24 +03:00
if !ok {
return
}
2019-02-22 15:55:11 +03:00
mapresult := parseMap(key)
result = append(result, mapresult)
2019-02-08 18:02:24 +03:00
})
return result, nil
2019-02-08 15:24:54 +03:00
}
2019-02-22 15:55:11 +03:00
func (this *LuaParser) ParseMap(expr string) (map[string]interface{}, error) {
result := make(map[string]interface{})
err := this.state.DoString(expr)
if err != nil {
return result, err
}
lv := this.state.Get(-1)
tbl, ok := lv.(*lua.LTable)
if !ok {
return result, errors.New("parsing failed")
}
return parseMap(tbl), nil
}