Lua 调用 Go 语言 glua

码农软件 · 软件分类 · 其他开发相关 · 2019-10-24 16:59:35

软件介绍

自己写的一个go lua binding,为了使用方便,并没有封装很多lua api,只是是为了实现以下功能的简单封装:

  1. 可以将go函数注册到lua中去,扩展lua的函数库,参数自动转换,支持不定参数
  2. 可以同时执行多个lua脚本
  3. 从go中嗲用lua中的函数
  4. 支持bool、int、float、string类型的相互转换,其他类型可以传递到lua中,但是只能传回go中使用

这个binding很简单,下面的例子已经把所有能调用的API都调用了一遍:)

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, 
			"goprintln": fmt.Println,     // 不定参数函数
		},
	}
	if ok, err := L.Register(&tlib); !ok {
		fmt.Println(err.Error())
		return
	}
	// 执行lua语句
	L.Dostring(`gotest.PrintInt(gotest.NewInt(), "Int is")`) 
	// 执行lua脚本
	L.Dofile("test.lua")
	// 调用lua函数
	L.Call("gotest.goprintln", "Call lua function.", 123456)
}

lua脚本

--test.lua
gotest.goprintln(true, 123, "lua", gotest.NewInt())

如果使用上有什么问题,请直接给我反馈,谢谢!

本文地址:https://codercto.com/soft/d/17472.html

Ethnography and Virtual Worlds

Ethnography and Virtual Worlds

Tom Boellstorff、Bonnie Nardi、Celia Pearce、T. L. Taylor / Princeton University Press / 2012-9-16 / GBP 21.00

"Ethnography and Virtual Worlds" is the only book of its kind - a concise, comprehensive, and practical guide for students, teachers, designers, and scholars interested in using ethnographic methods t......一起来看看 《Ethnography and Virtual Worlds》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

在线进制转换器
在线进制转换器

各进制数互转换器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具