最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
一个goluabinding完工
时间:2026-08-20 08:06:50 编辑:袖梨 来源:一聚教程网
最近对go语言比较感兴趣,想试用go来做点东西,go做主框架,动态加载一些程序来执行。由于现在go语言不支持go模块的动态链接,所以需要选用一个脚本语言来补充,找了一下,感觉lua比较符合要求,虚拟机比较小,可以同时开多个执行多个lua脚本。于是就找了一下go对lua的binding,找到golua,但是已经好久没更新了,现在go1下编译都通不过,修改了一下通过来,结果发现不能注册go函数到lua中执行。。。

不得已,就想自己写一个,希望他能满足一下要求:
- 可以将go函数注册到lua中去,扩展lua的函数库
- 可以同时执行多个lua脚本
- 支持bool、int、float、string类型的相互转换,其他类型先不考虑
- 从go中调用lua中的函数
- 其他类型都转的lua中的userdate,只能传回go中使用。
- 不定参数支持
package mainimport (
"fmt"
"glua"
)
type Int struct {
I int
}
func NewInt() *Int {
return &Int{10}
}
func (i Int) PrintInt(str string) {
fmt.Println(str, i.I)
}
func main() {
L := glua.NewState()
L.Openlibs()
var tlib = glua.Libfuncs{
"gotest", // lib name
map[string]interface{}{
"NewInt": NewInt, // lua function name, go function
"PrintInt": (*Int).PrintInt, // lua function name, go function
"goprintln": fmt.Println,
},
}
if ok, err := L.Register(&tlib); !ok {
fmt.Println(err.Error())
return
}
L.Dostring(`gotest.PrintInt(gotest.NewInt(), "Int is")`)
L.Dofile("test.lua")
L.Call("gotest.goprintln", "Call lua function.", 123456)
}
--test.luagotest.goprintln(true, 123, "lua", gotest.NewInt())
在code.google.com/p/glua可以看到全部代码,编译需要用luajit,因为lua5.1编译出来是静态库,而go1不支持链接静态库,所以选用luajit了。