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条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗