github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/examples/extend/main.go (about) 1 package main 2 3 import ( 4 "os" 5 6 "github.com/arnodel/golua/lib/base" 7 rt "github.com/arnodel/golua/runtime" 8 ) 9 10 // This is the Go function that we are going to call from Lua. Its inputs are: 11 // 12 // - t: the thread the function is running in. 13 // 14 // - c: the go continuation that represents the context the function is called 15 // in. It contains the arguments to the function and the next continuation 16 // (the one which receives the values computed by this function). 17 // 18 // It returns the next continuation on success, else an error. 19 func addints(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) { 20 var x, y int64 21 22 // First check there are two arguments 23 err := c.CheckNArgs(2) 24 if err == nil { 25 // Ok then try to convert the first argument to a lua integer. 26 x, err = c.IntArg(0) 27 } 28 if err == nil { 29 // Ok then try to convert the first argument to a lua integer. 30 y, err = c.IntArg(1) 31 } 32 if err != nil { 33 // Some error occurred, we return it in our context 34 return nil, err 35 } 36 // Arguments parsed! First get the next continuation. 37 next := c.Next() 38 39 // Then compute the result and push it to the continuation. 40 t.Push1(next, rt.IntValue(x+y)) 41 42 // Finally return the next continuation. 43 return next, nil 44 45 // Note: the last 3 steps could have been written as: 46 // return c.PushingNext(x + y), nil 47 } 48 49 func main() { 50 // First we obtain a new Lua runtime which outputs to stdout 51 r := rt.New(os.Stdout) 52 53 // Load the basic library into the runtime (we need print) 54 base.Load(r) 55 56 // Then we add our addints function to the global environment of the 57 // runtime. 58 r.SetEnvGoFunc(r.GlobalEnv(), "addints", addints, 2, false) 59 60 // This is the chunk we want to run. It calls the addints function. 61 source := []byte(`print("hello", addints(40, 2))`) 62 63 // Compile the chunk. 64 chunk, _ := r.CompileAndLoadLuaChunk("test", source, rt.TableValue(r.GlobalEnv())) 65 66 // Run the chunk in the runtime's main thread. It should output 42! 67 _, _ = rt.Call1(r.MainThread(), rt.FunctionValue(chunk)) 68 }