一个go lua binding完工

  最近对go语言比较感兴趣,想试用go来作点东西,go作主框架,动态加载一些程序来执行。因为如今go语言不支持go模块的动态连接,因此须要选用一个脚本语言来补充,找了一下,感受lua比较符合要求,虚拟机比较小,能够同时开多个执行多个lua脚本。因而就找了一下go对lua的binding,找到golua,可是已经很久没更新了,如今go1下编译都通不过,修改了一下经过来,结果发现不能注册go函数到lua中执行。。。框架

  不得已,就想本身写一个,但愿他能知足一下要求:函数

  1. 能够将go函数注册到lua中去,扩展lua的函数库
  2. 能够同时执行多个lua脚本
  3. 支持bool、int、float、string类型的相互转换,其余类型先不考虑
  以后又添加:
  1. 从go中调用lua中的函数
  2. 其余类型都转的lua中的userdate,只能传回go中使用。
  3. 不定参数支持
  不过我对go和lua都是新手。。。因而看了很多go和lua的文档,参考了golua和lua5.1的部分实现,终于写完了,感受还不错:

package main

import (
	"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.lua
gotest.goprintln(true, 123, "lua", gotest.NewInt())



  在code.google.com/p/glua能够看到所有代码,编译须要用luajit,由于lua5.1编译出来是静态库,而go1不支持连接静态库,因此选用luajit了。
相关文章
相关标签/搜索