diff --git a/define.go b/define.go index e37a7e9..42241c1 100644 --- a/define.go +++ b/define.go @@ -10,5 +10,5 @@ package lua // ScriptParam 脚本参数 type ScriptParam struct { Name string `json:"name"` // 参数名称 - Value string `json:"value"` // 参数值 + Value any `json:"value"` // 参数值 } diff --git a/vm.go b/vm.go index e3dc8b0..46507a8 100644 --- a/vm.go +++ b/vm.go @@ -94,7 +94,14 @@ func (v *VM) GetVm(scriptParamList ...ScriptParam) *luaCompile.LState { v.l.Lock() defer v.l.Unlock() if len(v.pool) == 0 { - return luaCompile.NewState() + // 基于libs预导入lua的常用模块 + vm := luaCompile.NewState() + libs.Preload(vm) + // 设置脚本参数 + for _, itemParam := range scriptParamList { + vm.SetGlobal(itemParam.Name, luar.New(vm, itemParam.Value)) + } + return vm } l := v.pool[len(v.pool)-1] // 基于libs预导入lua的常用模块 @@ -102,7 +109,6 @@ func (v *VM) GetVm(scriptParamList ...ScriptParam) *luaCompile.LState { // 设置脚本参数 for _, itemParam := range scriptParamList { l.SetGlobal(itemParam.Name, luar.New(l, itemParam.Value)) - } v.pool = v.pool[:len(v.pool)-1] return l diff --git a/vm_test.go b/vm_test.go index 0040a8e..8506e56 100644 --- a/vm_test.go +++ b/vm_test.go @@ -14,7 +14,7 @@ import ( func TestNewVm(t *testing.T) { scriptTable := map[string]string{ - "json": `local json = require("dkjson") + "json": `local json = require("json") local lua_table = { name = "wx771720", age = 18, @@ -55,3 +55,22 @@ end _, err = VMInstance.RunPreCompileScript("http") fmt.Println(err) } + +func TestNewVM_Map_Param(t *testing.T) { + scriptTable := map[string]string{ + "json": ` +local json = require("json") +print(jsonData.name) +local json_str = json.encode(jsonData) +print(json_str) -- 输出JSON字符串`, + } + if err := InitVM(1024, nil, scriptTable); err != nil { + panic(err.Error()) + } + + _, err := VMInstance.RunPreCompileScript("json", ScriptParam{Name: "jsonData", Value: map[string]any{ + "name": "白茶清欢", + }}) + fmt.Println(err) + +}