github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/lib/golib/lua_test.go (about)

     1  package golib_test
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	"github.com/arnodel/golua/lib"
     8  	"github.com/arnodel/golua/lib/golib"
     9  	"github.com/arnodel/golua/luatesting"
    10  	rt "github.com/arnodel/golua/runtime"
    11  )
    12  
    13  type TestStruct struct {
    14  	Age  int
    15  	Name string
    16  }
    17  
    18  func (t TestStruct) Descr() string {
    19  	return fmt.Sprintf("age: %d, name: %s", t.Age, t.Name)
    20  }
    21  
    22  func (t *TestStruct) Mix(u *TestStruct) *TestStruct {
    23  	return &TestStruct{
    24  		Age:  t.Age + u.Age,
    25  		Name: t.Name + "-" + u.Name,
    26  	}
    27  }
    28  
    29  func twice(f func(int) int) func(int) int {
    30  	return func(n int) int {
    31  		return f(f(n))
    32  	}
    33  }
    34  
    35  func setup(r *rt.Runtime) func() {
    36  	cleanup := lib.LoadAll(r)
    37  	g := r.GlobalEnv()
    38  	r.SetEnv(g, "hello", rt.StringValue("world"))
    39  	r.SetEnv(g, "double", golib.NewGoValue(r, func(x int) int { return 2 * x }))
    40  	r.SetEnv(g, "polly", golib.NewGoValue(r, TestStruct{Age: 10, Name: "Polly"}))
    41  	r.SetEnv(g, "ben", golib.NewGoValue(r, &TestStruct{Age: 5, Name: "Ben"}))
    42  	r.SetEnv(g, "mapping", golib.NewGoValue(r, map[string]int{"answer": 42}))
    43  	r.SetEnv(g, "slice", golib.NewGoValue(r, []string{"I", "am", "here"}))
    44  	r.SetEnv(g, "sprintf", golib.NewGoValue(r, fmt.Sprintf))
    45  	r.SetEnv(g, "twice", golib.NewGoValue(r, twice))
    46  	r.SetEnv(g, "panic", golib.NewGoValue(r, func() { panic("OMG") }))
    47  	return cleanup
    48  }
    49  
    50  func TestGoLib(t *testing.T) {
    51  	luatesting.RunLuaTestsInDir(t, "lua", setup)
    52  }