Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "unsafe"
- lua "github.com/aarzilli/golua/lua"
- )
- type Book struct {
- Id int64
- Title string
- }
- func BookCreate(L *lua.State) int {
- title := L.ToString(1)
- book := (*Book)(L.NewUserdata(uintptr(unsafe.Sizeof(Book{}))))
- L.LGetMetaTable("Book")
- L.SetMetaTable(-2)
- book.Id = 1;
- book.Title = title;
- return 1
- }
- func BookToString(L *lua.State) int {
- book := (*Book)(L.ToUserdata(1))
- L.PushString(fmt.Sprintf("Book(Id=%d, Title=\"%s\")", book.Id, book.Title))
- return 1
- }
- const test = `
- local book = Book.Create('Le Petit Prince')
- print(book)
- print(book:__tostring())
- print(Book.__tostring(book))
- `
- func main() {
- L := lua.NewState()
- defer L.Close()
- L.OpenLibs()
- L.NewMetaTable("Book")
- L.PushString("__index")
- L.PushValue(-2)
- L.SetTable(-3)
- L.SetMetaMethod("Create", BookCreate)
- L.SetMetaMethod("__tostring", BookToString)
- L.SetGlobal("Book")
- err := L.DoString(test)
- if err != nil {
- fmt.Println("Error: ", err)
- }
- }
Add Comment
Please, Sign In to add comment