温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Golang中使用lua进行扩展的示例

发布时间:2021-02-20 11:14:54 来源:亿速云 阅读:161 作者:小新 栏目:编程语言

这篇文章主要介绍Golang中使用lua进行扩展的示例,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

数据类型

lua中的数据类型与golang中的数据类型对应关系作者已经在文档中说明,值得注意的是类型是以L开头的,类型的名称是以LT开头的.

golang中的数据转换为lua中的数据就必须转换为L开头的类型:

str := "hello"
num := 10
L.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)

Table

关于lua中的table是一个很强大的东西,项目对table也提供了很多方法的支持比如获取一个字段,添加一个字段.这里推荐使用gluamapper,可以将tabl转换为golang中的结构体或者map[string]interface{}类型,这里使用了作者提供的例子:

type Role struct {
 Name string
}

type Person struct {
 Name  string
 Age  int
 WorkPlace string
 Role  []*Role
}

L := lua.NewState()
if err := L.DoString(`
person = {
 name = "Michel",
 age = "31", -- weakly input
 work_place = "San Jose",
 role = {
 {
  name = "Administrator"
 },
 {
  name = "Operator"
 }
 }
}
`); err != nil {
 panic(err)
}
var person Person
if err := gluamapper.Map(L.GetGlobal("person").(*lua.LTable), &person); err != nil {
 panic(err)
}
fmt.Printf("%s %d", person.Name, person.Age)

模块的加载与使用

项目中提供了lua基本模块,调用OpenLibs就可以加载这些模块,其中包括io,math,os,debug等.如果想自己加载可以使用SkipOpenLibs参数跳过.

如果想开发自己的库,文档中也做出了说明:

func Loader(L *lua.LState) int {
 //注册模块中的导出函数
 mod := L.SetFuncs(L.NewTable(), exports)
 L.Push(mod)
 return 1
}

var exports = map[string]lua.LGFunction{
 "myfunc": myfunc,
}

func myfunc(L *lua.LState) int {
 return 0
}
//这里就可以加载mymodule模块
L.PreloadModule("mymodule", mymodule.Loader)

以上是“Golang中使用lua进行扩展的示例”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI