du532861657 2016-01-17 18:07
浏览 95
已采纳

golua-使用定义的方法声明lua类

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

  1. How to create lua class equivalent to one described in A Simplified Way to Declare Lua Classes?
  2. How to add "magic methods" to class like __tostring here
  • 写回答

2条回答 默认 最新

  • douba05167 2016-01-17 23:15
    关注

    I have not used go, but it looks like you never set Book as a metatable for the new book you create. Im fairly sure this does not happen automatically.

    See an example I found here https://github.com/stevedonovan/luar/blob/master/luar.go#L52

    What is important here is that when a userdata or any object is made (your book), you need to get the global metatable and then set it as metatable with L.SetMetaTable(-2)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料