github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/examples/embed/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	rt "github.com/arnodel/golua/runtime"
     8  )
     9  
    10  func main() {
    11  	// First we obtain a new Lua runtime which outputs to stdout
    12  	r := rt.New(os.Stdout)
    13  
    14  	// This is the chunk we want to run.  It returns an adding function.
    15  	source := []byte(`return function(x, y) return x + y end`)
    16  
    17  	// Compile the chunk. Note that compiling doesn't require a runtime.
    18  	chunk, _ := r.CompileAndLoadLuaChunk("test", source, rt.TableValue(r.GlobalEnv()))
    19  
    20  	// Run the chunk in the runtime's main thread.  Its output is the Lua adding
    21  	// function.
    22  	add, _ := rt.Call1(r.MainThread(), rt.FunctionValue(chunk))
    23  
    24  	// Now, run the Lua function in the main thread.
    25  	sum, _ := rt.Call1(r.MainThread(), add, rt.IntValue(40), rt.IntValue(2))
    26  
    27  	// --> 42
    28  	fmt.Println(sum.AsInt())
    29  }