residentsleeper/scripting/config/config.go

97 lines
1.3 KiB
Go
Raw Normal View History

package config
import (
"github.com/yuin/gopher-lua"
"io/ioutil"
luajson "layeh.com/gopher-json"
"os"
"path"
)
var (
BasePath string
)
func Loader(L *lua.LState) int {
// register functions to the table
mod := L.SetFuncs(L.NewTable(), exports)
// returns the module
L.Push(mod)
return 1
}
var exports = map[string]lua.LGFunction{
"load": loadFunc,
"save": saveFunc,
}
func loadFunc(L *lua.LState) int {
name := L.CheckString(1)
f, err := os.Open(path.Join(BasePath, name+".json"))
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
v, err := luajson.Decode(L, b)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
L.Push(v)
L.Push(lua.LNil)
return 2
}
func saveFunc(L *lua.LState) int {
name := L.CheckString(1)
value := L.CheckAny(2)
f, err := os.Create(path.Join(BasePath, name+".json"))
if err != nil {
L.Push(lua.LString(err.Error()))
return 1
}
b, err := luajson.Encode(value)
if err != nil {
L.Push(lua.LString(err.Error()))
return 1
}
_, err = f.Write(b)
if err != nil {
L.Push(lua.LString(err.Error()))
return 1
}
err = f.Close()
if err != nil {
L.Push(lua.LString(err.Error()))
return 1
}
return 0
}