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://www.codercto.com/soft/d/17472.html

Web Standards Creativity

Web Standards Creativity

Andy Budd、Dan Rubin、Jeff Croft、Cameron Adams、Ethan Marcotte、Andy Clarke、Ian Lloyd、Mark Boulton、Rob Weychert、Simon Collison、Derek Featherstone / friends of ED / March 19, 2007 / $49.99

Book Description * Be inspired by 10 web design lessons from 10 of the world's best web designers * Get creative with cutting-edge XHTML, CSS, and DOM scripting techniques * Learn breathtakin......一起来看看 《Web Standards Creativity》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具