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

     1  package luar
     2  
     3  import (
     4  	"github.com/dfcfw/lua"
     5  )
     6  
     7  func ExampleLState() {
     8  	const code = `
     9  	print(sum(1, 2, 3, 4, 5))
    10  	`
    11  
    12  	L := lua.NewState()
    13  	defer L.Close()
    14  
    15  	sum := func(L *lua.LState) int {
    16  		total := 0
    17  		for i := 1; i <= L.GetTop(); i++ {
    18  			total += L.CheckInt(i)
    19  		}
    20  		L.Push(lua.LNumber(total))
    21  		return 1
    22  	}
    23  
    24  	L.SetGlobal("sum", New(L, sum))
    25  
    26  	if err := L.DoString(code); err != nil {
    27  		panic(err)
    28  	}
    29  	// Output:
    30  	// 15
    31  }
    32  
    33  func ExampleNewType() {
    34  	L := lua.NewState()
    35  	defer L.Close()
    36  
    37  	type Song struct {
    38  		Title  string
    39  		Artist string
    40  	}
    41  
    42  	L.SetGlobal("Song", NewType(L, Song{}))
    43  	if err := L.DoString(`
    44  		s = Song()
    45  		s.Title = "Montana"
    46  		s.Artist = "Tycho"
    47  		print(s.Artist .. " - " .. s.Title)
    48  	`); err != nil {
    49  		panic(err)
    50  	}
    51  	// Output:
    52  	// Tycho - Montana
    53  }