Guest User

Untitled

a guest
Jan 18th, 2016
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.10 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "unsafe"
  6.     lua "github.com/aarzilli/golua/lua"
  7. )
  8.  
  9. type Book struct {
  10.     Id int64
  11.     Title string
  12. }
  13.  
  14. func BookCreate(L *lua.State) int {
  15.     title := L.ToString(1)
  16.     book := (*Book)(L.NewUserdata(uintptr(unsafe.Sizeof(Book{}))))
  17.  
  18.     L.LGetMetaTable("Book")
  19.     L.SetMetaTable(-2)
  20.  
  21.     book.Id = 1;
  22.     book.Title = title;
  23.  
  24.     return 1
  25. }
  26.  
  27. func BookToString(L *lua.State) int {
  28.     book := (*Book)(L.ToUserdata(1))
  29.     L.PushString(fmt.Sprintf("Book(Id=%d, Title=\"%s\")", book.Id, book.Title))
  30.  
  31.     return 1
  32. }
  33.  
  34. const test = `
  35.     local book = Book.Create('Le Petit Prince')
  36.     print(book)
  37.     print(book:__tostring())
  38.     print(Book.__tostring(book))
  39. `
  40.  
  41. func main() {
  42.     L := lua.NewState()
  43.     defer L.Close()
  44.     L.OpenLibs()
  45.  
  46.     L.NewMetaTable("Book")
  47.     L.PushString("__index")
  48.     L.PushValue(-2)
  49.     L.SetTable(-3)
  50.     L.SetMetaMethod("Create", BookCreate)
  51.     L.SetMetaMethod("__tostring", BookToString)
  52.     L.SetGlobal("Book")
  53.  
  54.     err := L.DoString(test)
  55.     if err != nil {
  56.         fmt.Println("Error: ", err)
  57.     }
  58. }
Add Comment
Please, Sign In to add comment