执行lua脚本增加传参能力
This commit is contained in:
16
vm.go
16
vm.go
@ -13,6 +13,7 @@ import (
|
||||
luaCompile "github.com/yuin/gopher-lua"
|
||||
"github.com/yuin/gopher-lua/ast"
|
||||
"github.com/yuin/gopher-lua/parse"
|
||||
luar "layeh.com/gopher-luar"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@ -89,7 +90,7 @@ func (v *VM) RemoveScript(scriptID string) {
|
||||
}
|
||||
|
||||
// GetVm 获取一个VM实例
|
||||
func (v *VM) GetVm() *luaCompile.LState {
|
||||
func (v *VM) GetVm(scriptParamList ...ScriptParam) *luaCompile.LState {
|
||||
v.l.Lock()
|
||||
defer v.l.Unlock()
|
||||
if len(v.pool) == 0 {
|
||||
@ -98,6 +99,11 @@ func (v *VM) GetVm() *luaCompile.LState {
|
||||
l := v.pool[len(v.pool)-1]
|
||||
// 基于libs预导入lua的常用模块
|
||||
libs.Preload(l)
|
||||
// 设置脚本参数
|
||||
for _, itemParam := range scriptParamList {
|
||||
l.SetGlobal(itemParam.Name, luar.New(l, itemParam.Value))
|
||||
|
||||
}
|
||||
v.pool = v.pool[:len(v.pool)-1]
|
||||
return l
|
||||
}
|
||||
@ -119,7 +125,7 @@ func (v *VM) Shutdown() {
|
||||
}
|
||||
|
||||
// RunPreCompileScript 执行预编译过的脚本
|
||||
func (v *VM) RunPreCompileScript(scriptID string) (*luaCompile.LState, error) {
|
||||
func (v *VM) RunPreCompileScript(scriptID string, scriptParamList ...ScriptParam) (*luaCompile.LState, error) {
|
||||
var (
|
||||
err error
|
||||
proto *luaCompile.FunctionProto
|
||||
@ -131,7 +137,7 @@ func (v *VM) RunPreCompileScript(scriptID string) (*luaCompile.LState, error) {
|
||||
return nil, fmt.Errorf("preComplier script %s not found", scriptID)
|
||||
}
|
||||
v.scriptLock.Unlock()
|
||||
l := v.GetVm()
|
||||
l := v.GetVm(scriptParamList...)
|
||||
lFunc := l.NewFunctionFromProto(proto)
|
||||
l.Push(lFunc)
|
||||
if err = l.PCall(0, luaCompile.MultRet, nil); nil != err {
|
||||
@ -146,8 +152,8 @@ func (v *VM) RunPreCompileScript(scriptID string) (*luaCompile.LState, error) {
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 18:08 2024/11/14
|
||||
func (v *VM) Run(script string) (*luaCompile.LState, error) {
|
||||
l := v.GetVm()
|
||||
func (v *VM) Run(script string, scriptParamList ...ScriptParam) (*luaCompile.LState, error) {
|
||||
l := v.GetVm(scriptParamList...)
|
||||
if err := l.DoString(script); err != nil {
|
||||
// 直接归还实例
|
||||
l.Close()
|
||||
|
||||
Reference in New Issue
Block a user