github.com/dfcfw/lua@v0.0.0-20230325031207-0cc7ffb7b8b9/luar/array_test.go (about)

     1  package luar
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/dfcfw/lua"
     7  )
     8  
     9  type TestArrayOneString [1]string
    10  
    11  func (o TestArrayOneString) Get() string {
    12  	return o[0]
    13  }
    14  
    15  func Test_array(t *testing.T) {
    16  	L := lua.NewState()
    17  	defer L.Close()
    18  
    19  	type Elem struct {
    20  		V [2]string
    21  	}
    22  
    23  	var elem Elem
    24  	elem.V[0] = "Hello"
    25  	elem.V[1] = "World"
    26  
    27  	var arr TestArrayOneString
    28  	arr[0] = "Test"
    29  
    30  	L.SetGlobal("e", New(L, &elem))
    31  	L.SetGlobal("arr", New(L, arr))
    32  
    33  	testReturn(t, L, `return #e.V, e.V[1], e.V[2]`, "2", "Hello", "World")
    34  	testReturn(t, L, `e.V[1] = "World"; e.V[2] = "Hello"`)
    35  	testReturn(t, L, `return #e.V, e.V[1], e.V[2]`, "2", "World", "Hello")
    36  
    37  	testReturn(t, L, `return #arr, arr[1]`, "1", "Test")
    38  	testReturn(t, L, `return arr:Get()`, "Test")
    39  
    40  	testError(t, L, `e.V[1] = nil`, "cannot use nil as type string")
    41  }
    42  
    43  func Test_array_iterator(t *testing.T) {
    44  	L := lua.NewState()
    45  	defer L.Close()
    46  
    47  	a := [...]string{"x", "y"}
    48  
    49  	L.SetGlobal("a", New(L, a))
    50  	L.SetGlobal("ap", New(L, &a))
    51  
    52  	testReturn(t, L, `local itr = a(); local a, b = itr(); local c, d = itr(); return a, b, c, d`, "1", "x", "2", "y")
    53  	testReturn(t, L, `local itr = ap(); local a, b = itr(); local c, d = itr(); return a, b, c, d`, "1", "x", "2", "y")
    54  }
    55  
    56  func Test_array_eq(t *testing.T) {
    57  	L := lua.NewState()
    58  	defer L.Close()
    59  
    60  	a := [...]string{"x", "y"}
    61  	b := [...]string{"x", "y"}
    62  
    63  	L.SetGlobal("a", New(L, a))
    64  	L.SetGlobal("ap", New(L, &a))
    65  	L.SetGlobal("b", New(L, b))
    66  	L.SetGlobal("bp", New(L, &b))
    67  
    68  	testReturn(t, L, `return a == b`, "true")
    69  	testReturn(t, L, `return a ~= b`, "false")
    70  	testReturn(t, L, `return ap == nil`, "false")
    71  	testReturn(t, L, `return ap == bp`, "false")
    72  }