github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/runtime/wrappers.go (about) 1 package runtime 2 3 import ( 4 "io" 5 ) 6 7 // DoInContext creates a *Runtime r with the constraints from the 8 // RuntimeContextDef def, calls f(r) and returns two things: A RuntimeContext 9 // instance ctx whose status tells us the outcome (done, killed or error) and in 10 // case of error, a non-nil error value. 11 func DoInContext(f func(r *Runtime) error, def RuntimeContextDef, stdout io.Writer, opts ...RuntimeOption) (ctx RuntimeContext, err error) { 12 r := New(stdout, opts...) 13 defer r.Close(nil) 14 ctx, err = r.MainThread().CallContext(def, func() error { 15 return f(r) 16 }) 17 return 18 } 19 20 // RunChunk1 runs source code in a runtime constrained by def. It returns the 21 // value returned by the chunk and possibly an error if execution failed 22 // (including when the runtime was killed). 23 func RunChunk1(source []byte, def RuntimeContextDef, stdout io.Writer, opts ...RuntimeOption) (v Value, err error) { 24 _, err = DoInContext(func(r *Runtime) error { 25 env := TableValue(r.GlobalEnv()) 26 chunk, err := r.CompileAndLoadLuaChunk("code", source, env) 27 if err != nil { 28 return err 29 } 30 v, err = Call1(r.MainThread(), FunctionValue(chunk)) 31 return err 32 }, def, stdout, opts...) 33 return v, err 34 }