github.com/dfcfw/lua@v0.0.0-20230325031207-0cc7ffb7b8b9/luar/helpers_test.go (about) 1 package luar 2 3 import ( 4 "runtime/debug" 5 "strconv" 6 "strings" 7 "testing" 8 9 "github.com/dfcfw/lua" 10 ) 11 12 type StructTestPerson struct { 13 Name string 14 Age int 15 Friend *StructTestPerson 16 LastAddSum int 17 } 18 19 func (p StructTestPerson) Hello() string { 20 return "Hello, " + p.Name 21 } 22 23 func (p StructTestPerson) String() string { 24 return p.Name + " (" + strconv.Itoa(p.Age) + ")" 25 } 26 27 func (p *StructTestPerson) AddNumbers(L *LState) int { 28 sum := 0 29 for i := L.GetTop(); i >= 1; i-- { 30 sum += L.CheckInt(i) 31 } 32 L.Push(lua.LString(p.Name + " counts: " + strconv.Itoa(sum))) 33 p.LastAddSum = sum 34 return 1 35 } 36 37 func (p *StructTestPerson) IncreaseAge() { 38 p.Age++ 39 } 40 41 func testReturn(t *testing.T, L *lua.LState, code string, values ...string) { 42 t.Helper() 43 top := L.GetTop() 44 if err := L.DoString(code); err != nil { 45 t.Fatalf("%s\n\n%s", err, debug.Stack()) 46 } 47 48 valid := true 49 newTop := L.GetTop() 50 51 if newTop-top != len(values) { 52 valid = false 53 } else { 54 for i, expect := range values { 55 // TODO: strong typing 56 val := L.Get(top + i + 1).String() 57 if val != expect { 58 valid = false 59 } 60 } 61 } 62 63 if !valid { 64 got := make([]string, newTop-top) 65 for i := 0; i < len(got); i++ { 66 got[i] = L.Get(top + i + 1).String() 67 } 68 69 t.Fatalf("bad return values: expecting %#v, got %#v\n\n%s", values, got, debug.Stack()) 70 } 71 72 L.SetTop(top) 73 } 74 75 func testError(t *testing.T, L *lua.LState, code, error string) { 76 t.Helper() 77 err := L.DoString(code) 78 if err == nil { 79 t.Fatalf("expecting error, got nil\n\n%s", debug.Stack()) 80 } 81 82 if s := err.Error(); strings.Index(s, error) == -1 { 83 t.Fatalf("error substring '%s' not found in '%s'\n\n%s", error, s, debug.Stack()) 84 } 85 }