增加执行脚本 + 获取脚本返回结果的方法

This commit is contained in:
白茶清欢 2024-11-14 18:22:25 +08:00
parent 13f78896c0
commit 316e120490
4 changed files with 95 additions and 1 deletions

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Created by .ignore support plugin (hsz.mobi)
### Go template
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
.idea
.vscode
.fleet
release
logs
.scannerwork
.env

2
go.mod
View File

@ -2,4 +2,4 @@ module git.zhangdeman.cn/gateway/lua
go 1.23.3
require github.com/yuin/gopher-lua v1.1.1 // indirect
require github.com/yuin/gopher-lua v1.1.1

53
vm.go Normal file
View File

@ -0,0 +1,53 @@
// Package lua ...
//
// Description : lua ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-11-14 17:46
package lua
import (
luaCompile "github.com/yuin/gopher-lua"
)
func NewVm() *VM {
return &VM{luaVm: luaCompile.NewState()}
}
type VM struct {
luaVm *luaCompile.LState
}
// Run 运行脚本
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:08 2024/11/14
func (v *VM) Run(script string) error {
if err := v.luaVm.DoString(script); err != nil {
return err
}
return nil
}
// GetResultAndRemove 获取最后一个返回值, 并从结果中移除
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:20 2024/11/14
func (v *VM) GetResultAndRemove() luaCompile.LValue {
val := v.luaVm.Get(-1)
v.luaVm.Pop(1)
return val
}
// GetResultByIndex 根据索引获取返回值
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:21 2024/11/14
func (v *VM) GetResultByIndex(index int) luaCompile.LValue {
val := v.luaVm.Get(index)
return val
}

17
vm_test.go Normal file
View File

@ -0,0 +1,17 @@
// Package lua ...
//
// Description : lua ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-11-14 18:08
package lua
import (
"testing"
)
func TestNewVm(t *testing.T) {
v := NewVm()
v.Run(`print("hello world"); return "hahaha", "heiheihei"`)
}