I'm trying to use golua package to build an extension API for my application written in Go. My idea is to have several classes exposed to lua VM, for example Book
class:
local book = Book.Create("Le Petit Prince")
print(book)
book:save()
What I'm able to do now is just basic:
type Book struct {
Id int64
Title string
}
func BookCreate(L *lua.State) int {
title := L.ToString(1)
p := &Book{Id: 1, Title: title}
L.PushGoStruct(p)
return 1
}
func BookToString(L *lua.State) int {
book, _ := L.ToGoStruct(1).(*Book)
L.PushString(fmt.Sprintf("Book(Id=%d, Title=\"%s\")", book.Id, book.Title))
return 1
}
L := lua.NewState()
defer L.Close()
L.OpenLibs()
L.NewMetaTable("Book")
L.SetMetaMethod("Create", BookCreate)
L.SetMetaMethod("tostring", BookToString)
L.SetGlobal("Book")
Which allows me to do this:
local book = Book.Create("Le Petit Prince")
print(Book.tostring(book))
But not this:
local book = Book.Create("Le Petit Prince")
print(book:tostring())
// reflect: call of reflect.Value.Type on zero Value
My questions
- How to create lua class equivalent to one described in A Simplified Way to Declare Lua Classes?
- How to add "magic methods" to class like
__tostring
here