// Package lua ... // // Description : lua ... // // Author : go_developer@163.com<白茶清欢> // // Date : 2024-11-14 17:46 package lua import ( luaCompile "github.com/yuin/gopher-lua" "sync" ) 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 { l *sync.RWMutex pool []*luaCompile.LState } // 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 运行脚本 // // Author : go_developer@163.com<白茶清欢> // // Date : 18:08 2024/11/14 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 l, nil } // GetResultAndRemove 获取最后一个返回值, 并从结果中移除 func (v *VM) GetResultAndRemove(l *luaCompile.LState) luaCompile.LValue { val := l.Get(-1) l.Pop(1) return val } // GetResultByIndex 根据索引获取返回值 func (v *VM) GetResultByIndex(l *luaCompile.LState, index int) luaCompile.LValue { val := l.Get(index) return val }