调试脚本传参 + 全局包预导入

This commit is contained in:
白茶清欢 2025-05-12 21:56:00 +08:00
parent da61086725
commit 90d22fa94f
3 changed files with 29 additions and 4 deletions

View File

@ -10,5 +10,5 @@ package lua
// ScriptParam 脚本参数 // ScriptParam 脚本参数
type ScriptParam struct { type ScriptParam struct {
Name string `json:"name"` // 参数名称 Name string `json:"name"` // 参数名称
Value string `json:"value"` // 参数值 Value any `json:"value"` // 参数值
} }

10
vm.go
View File

@ -94,7 +94,14 @@ func (v *VM) GetVm(scriptParamList ...ScriptParam) *luaCompile.LState {
v.l.Lock() v.l.Lock()
defer v.l.Unlock() defer v.l.Unlock()
if len(v.pool) == 0 { 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] l := v.pool[len(v.pool)-1]
// 基于libs预导入lua的常用模块 // 基于libs预导入lua的常用模块
@ -102,7 +109,6 @@ func (v *VM) GetVm(scriptParamList ...ScriptParam) *luaCompile.LState {
// 设置脚本参数 // 设置脚本参数
for _, itemParam := range scriptParamList { for _, itemParam := range scriptParamList {
l.SetGlobal(itemParam.Name, luar.New(l, itemParam.Value)) l.SetGlobal(itemParam.Name, luar.New(l, itemParam.Value))
} }
v.pool = v.pool[:len(v.pool)-1] v.pool = v.pool[:len(v.pool)-1]
return l return l

View File

@ -14,7 +14,7 @@ import (
func TestNewVm(t *testing.T) { func TestNewVm(t *testing.T) {
scriptTable := map[string]string{ scriptTable := map[string]string{
"json": `local json = require("dkjson") "json": `local json = require("json")
local lua_table = { local lua_table = {
name = "wx771720", name = "wx771720",
age = 18, age = 18,
@ -55,3 +55,22 @@ end
_, err = VMInstance.RunPreCompileScript("http") _, err = VMInstance.RunPreCompileScript("http")
fmt.Println(err) 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)
}