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

     1  package luar
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/dfcfw/lua"
     7  )
     8  
     9  func Test_slice(t *testing.T) {
    10  	L := lua.NewState()
    11  	defer L.Close()
    12  
    13  	things := []string{
    14  		"cake",
    15  		"wallet",
    16  		"calendar",
    17  		"phone",
    18  		"speaker",
    19  	}
    20  
    21  	L.SetGlobal("things", New(L, things))
    22  
    23  	testReturn(t, L, `return #things, things[1], things[5]`, "5", "cake", "speaker")
    24  	if err := L.DoString(`things[1] = "cookie"`); err != nil {
    25  		t.Fatal(err)
    26  	}
    27  	if things[0] != "cookie" {
    28  		t.Fatalf(`expected things[0] = "cookie", got %s`, things[0])
    29  	}
    30  }
    31  
    32  func Test_slice_2(t *testing.T) {
    33  	L := lua.NewState()
    34  	defer L.Close()
    35  
    36  	items := make([]string, 0, 10)
    37  
    38  	L.SetGlobal("items", New(L, items))
    39  
    40  	testReturn(t, L, `return #items`, "0")
    41  	testReturn(t, L, `items = items + "hello" + "world"; return #items`, "2")
    42  	testReturn(t, L, `return items[1]`, "hello")
    43  	testReturn(t, L, `return items[2]`, "world")
    44  }
    45  
    46  func Test_slice_iterator(t *testing.T) {
    47  	L := lua.NewState()
    48  	defer L.Close()
    49  
    50  	s := []string{
    51  		"hello",
    52  		"there",
    53  	}
    54  
    55  	e := []string{}
    56  
    57  	L.SetGlobal("s", New(L, s))
    58  	L.SetGlobal("e", New(L, e))
    59  
    60  	testReturn(t, L, `local itr = s(); local a, b = itr(); local c, d = itr(); return a, b, c, d`, "1", "hello", "2", "there")
    61  	testReturn(t, L, `local itr = e(); local a, b = itr(); return a, b`, "nil", "nil")
    62  }