From d34aa09e8e70a7f8fe8b4e0bc481c59536a7cbaa Mon Sep 17 00:00:00 2001 From: TorchedSammy <38820196+TorchedSammy@users.noreply.github.com> Date: Mon, 28 Mar 2022 17:40:36 -0400 Subject: [PATCH] fix: handle errors in user config --- lua.go | 10 +++------- util/util.go | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/lua.go b/lua.go index dd585af..9c3bc20 100644 --- a/lua.go +++ b/lua.go @@ -4,6 +4,7 @@ import ( "fmt" "os" + "hilbish/util" "hilbish/golibs/bait" /* "hilbish/golibs/commander" @@ -71,14 +72,9 @@ func runConfig(confpath string) { if !interactive { return } - data, err := os.ReadFile(confpath) + err := util.DoFile(l, confpath) if err != nil { fmt.Fprintln(os.Stderr, err, "\nAn error has occured while loading your config! Falling back to minimal default config.") - chunk, _ := l.CompileAndLoadLuaChunk("", []byte(minimalconf), rt.TableValue(l.GlobalEnv())) - _, err := rt.Call1(l.MainThread(), rt.FunctionValue(chunk)) - fmt.Println(err) + util.DoString(l, minimalconf) } - chunk, _ := l.CompileAndLoadLuaChunk("", data, rt.TableValue(l.GlobalEnv())) - _, err = rt.Call1(l.MainThread(), rt.FunctionValue(chunk)) - fmt.Println("config", err) } diff --git a/util/util.go b/util/util.go index 14cd40c..9c032b5 100644 --- a/util/util.go +++ b/util/util.go @@ -1,6 +1,8 @@ package util import ( + "os" + "github.com/yuin/gopher-lua" rt "github.com/arnodel/golua/runtime" ) @@ -36,3 +38,20 @@ func SetField(rtm *rt.Runtime, module *rt.Table, field string, value rt.Value, d module.Set(rt.StringValue(field), value) } +func DoString(rtm *rt.Runtime, code string) error { + chunk, err := rtm.CompileAndLoadLuaChunk("", []byte(code), rt.TableValue(rtm.GlobalEnv())) + if chunk != nil { + _, err = rt.Call1(rtm.MainThread(), rt.FunctionValue(chunk)) + } + + return err +} + +func DoFile(rtm *rt.Runtime, filename string) error { + data, err := os.ReadFile(filename) + if err != nil { + return err + } + + return DoString(rtm, string(data)) +}