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

     1  package luar
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/dfcfw/lua"
     7  )
     8  
     9  func Test_map(t *testing.T) {
    10  	L := lua.NewState()
    11  	defer L.Close()
    12  
    13  	thangs := map[string]int{
    14  		"ABC": 123,
    15  		"DEF": 456,
    16  	}
    17  
    18  	L.SetGlobal("thangs", New(L, thangs))
    19  
    20  	testReturn(t, L, `return thangs.ABC`, "123")
    21  	testReturn(t, L, `return thangs.DEF`, "456")
    22  	testReturn(t, L, `return thangs.GHI`, "nil")
    23  
    24  	if err := L.DoString(`thangs.GHI = 789`); err != nil {
    25  		t.Fatal(err)
    26  	}
    27  
    28  	testReturn(t, L, `thangs.ABC = nil`)
    29  
    30  	if v := thangs["GHI"]; v != 789 {
    31  		t.Fatalf(`expecting thangs["GHI"] = 789, got %d`, v)
    32  	}
    33  
    34  	if _, ok := thangs["ABC"]; ok {
    35  		t.Fatal(`expecting thangs["ABC"] to be unset`)
    36  	}
    37  }
    38  
    39  func Test_map_iterator(t *testing.T) {
    40  	L := lua.NewState()
    41  	defer L.Close()
    42  
    43  	countries := map[string]string{
    44  		"JP": "Japan",
    45  		"CA": "Canada",
    46  		"FR": "France",
    47  	}
    48  
    49  	L.SetGlobal("countries", New(L, countries))
    50  
    51  	testReturn(t, L, `return #countries`, "3")
    52  
    53  	const code = `
    54  		sorted = {}
    55  		for k, v in countries() do
    56  			table.insert(sorted, v)
    57  		end
    58  		table.sort(sorted)`
    59  
    60  	if err := L.DoString(code); err != nil {
    61  		t.Fatal(err)
    62  	}
    63  
    64  	testReturn(t, L, `return #sorted, sorted[1], sorted[2], sorted[3]`, "3", "Canada", "France", "Japan")
    65  }
    66  
    67  type TestMapUsers map[uint32]string
    68  
    69  func (m TestMapUsers) Find(name string) uint32 {
    70  	for id, n := range m {
    71  		if name == n {
    72  			return id
    73  		}
    74  	}
    75  	return 0
    76  }
    77  
    78  func Test_map_methods(t *testing.T) {
    79  	L := lua.NewState()
    80  	defer L.Close()
    81  
    82  	type User struct {
    83  		Name string
    84  	}
    85  
    86  	users := TestMapUsers{
    87  		1: "Tim",
    88  	}
    89  
    90  	L.SetGlobal("users", New(L, users))
    91  
    92  	testReturn(t, L, `return users[1]`, "Tim")
    93  	testReturn(t, L, `return users[3]`, "nil")
    94  	testReturn(t, L, `return users:Find("Tim")`, "1")
    95  	testReturn(t, L, `return users:Find("Steve")`, "0")
    96  }