您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

golang lua怎么用

2026/6/13 13:29:05发布19次查看
github上有一个用golang编写的lua虚拟机,名字叫做gopher-lua。
lua中的数据类型与golang中的数据类型对应关系作者已经在文档中说明,值得注意的是类型是以l开头的,类型的名称是以lt开头的。                       (推荐学习:go)
golang中的数据转换为lua中的数据就必须转换为l开头的类型:
str := "hello"num := 10l.lstring(str)l.lnumber(float64(num))
lua中的数据转换为golang中的数据,项目提供了toint,checkstring之类的函数来进行转换,但是这都是必须提前知道类型的,如果不知道就必须进行类型判断:
value := l.get(1)switch value.type() {case lua.ltstring:case lua.lttable:....}
这里还可以使用gopher-luar来方便的进行类型转换.
golang和lua互相调用函数
golang中的函数必须转换为func(l *lua.state) int这种形式才能注入lua中,返回参数的int代表了返回参数的个数.
func hello(l *lua.state) int { //将返回参数压入栈中 l.push(lua.lstring("hello")) //返回参数为1个 return 1}//注入lua中l.setglobal("hello", l.newfunction(hello))
在golang中调用lua函数,lua脚本中需先定义这个函数,然后调用callbyparam进行调用:
//先获取lua中定义的函数fn := l.getglobal("hello")if err := l.callbyparam(lua.p{ fn: fn, nret: 1, protect: true, }, lua.lnumber(10)); err != nil { panic(err)}//这里获取函数返回值ret := l.get(-1)
以上就是golang lua怎么用的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product