lua VM管理,实例支持池化

This commit is contained in:
2025-05-12 14:45:08 +08:00
parent f4b1cf5e59
commit 8ad636517b

80
vm.go
View File

@ -9,23 +9,54 @@ package lua
import (
luaCompile "github.com/yuin/gopher-lua"
"sync"
)
func NewVm() *VM {
return &VM{luaVm: luaCompile.NewState()}
var (
VMInstance *VM
)
func InitVM(poolSize int) {
if poolSize <= 0 {
poolSize = 32
}
VMInstance = &VM{
l: &sync.RWMutex{},
pool: make([]*luaCompile.LState, 0),
}
}
type VM struct {
luaVm *luaCompile.LState
l *sync.RWMutex
pool []*luaCompile.LState
}
// Close 关闭虚拟机
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:26 2024/11/14
func (v *VM) Close() {
v.luaVm.Close()
// GetVm 获取一个VM实例
func (v *VM) GetVm() *luaCompile.LState {
v.l.Lock()
defer v.l.Unlock()
if len(v.pool) == 0 {
return luaCompile.NewState()
}
l := v.pool[len(v.pool)-1]
v.pool = v.pool[:len(v.pool)-1]
return l
}
// Close 关闭指定虚拟机
func (v *VM) Close(l *luaCompile.LState) {
l.Close()
v.l.Lock()
defer v.l.Unlock()
// 实例放回实例实例池
v.pool = append(v.pool, l)
}
// Shutdown 关闭全部虚拟机
func (v *VM) Shutdown() {
for _, item := range v.pool {
item.Close()
}
}
// Run 运行脚本
@ -33,30 +64,25 @@ func (v *VM) Close() {
// 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
func (v *VM) Run(script string) (*luaCompile.LState, error) {
l := v.GetVm()
if err := l.DoString(script); err != nil {
// 直接归还实例
l.Close()
return nil, err
}
return nil
return l, 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)
func (v *VM) GetResultAndRemove(l *luaCompile.LState) luaCompile.LValue {
val := l.Get(-1)
l.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)
func (v *VM) GetResultByIndex(l *luaCompile.LState, index int) luaCompile.LValue {
val := l.Get(index)
return val
}